Created
January 18, 2020 20:06
-
-
Save vlad-bezden/60c3ce445d20a0a32351bc53c0d55ebf to your computer and use it in GitHub Desktop.
Performance tests of 'find' and 'index' Python functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Performance tests of 'find' and 'index' functions. | |
Results: | |
using_index t = 0.0259 sec | |
using_index t = 0.0290 sec | |
using_index t = 0.6851 sec | |
using_find t = 0.0301 sec | |
using_find t = 0.0282 sec | |
using_find t = 0.6875 sec | |
Summary: | |
Both (find and index) functions have the same performance. | |
""" | |
def using_index(text: str, find: str) -> str: | |
"""Returns index position if found otherwise raises ValueError.""" | |
return text.index(find) | |
def using_find(text: str, find: str) -> str: | |
"""Returns index position if found otherwise -1.""" | |
return text.find(find) | |
if __name__ == "__main__": | |
from timeit import timeit | |
texts = [ | |
"short text to search" * 10, | |
"long text to search" * 10000, | |
"long_text_with_find_at_the_end" * 10000 + " to long", | |
] | |
for f in [using_index, using_find]: | |
for text in texts: | |
t = timeit(stmt="f(text, ' ')", number=10000, globals=globals()) | |
print(f"{f.__name__} {t = :.4f} sec") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment