Skip to content

Instantly share code, notes, and snippets.

@n8henrie
Last active November 22, 2016 18:38
Show Gist options
  • Save n8henrie/db6880e2c84df153c5ae19d5dba16757 to your computer and use it in GitHub Desktop.
Save n8henrie/db6880e2c84df153c5ae19d5dba16757 to your computer and use it in GitHub Desktop.
Gist of simple timing comparisons in Python
"""time_stuff.py :: A bunch of `timeit` comparisons for different snippets.
The module just loads the tests, so you can run specific examples interactively
if desired:
$ python3 -i <(curl -s https://gist.githubusercontent.com/n8henrie/db6880e2c84df153c5ae19d5dba16757/raw)
>>> find_vs_split_vs_re()
Best of 10000 runs over 5 repeats
test_find: 0.0087874069577083
test_split: 0.013382209988776594
test_re: 0.02201515296474099
"""
import timeit
import functools
def find_vs_split_vs_re():
def test_find(text, s, e):
start_find = text.find(s)
end_find = text.find(e, start_find + len(s))
if -1 in (start_find, end_find):
return ""
else:
return text[start_find + len(s):end_find]
def test_split(text, leader, splitter):
chunks = text.split(splitter)
for idx, chunk in enumerate(chunks):
if chunk.endswith(leader):
return chunks[idx + 1]
def test_re(text, regex):
# Include the additional time of the import in the test
import re
regex_c = re.compile(regex)
return re.search(regex, text).group(1)
# with open('index.html') as f:
# text = f.read()
text = '<script src="/asdf.js"></script>'
test_find_p = functools.partial(test_find, text, '<script src="', '"')
test_split_p = functools.partial(test_split, text, '<script src="', '"')
test_re_p = functools.partial(test_re, text, r'<script src="([^"]+)"')
number = 10000
repeat = 5
print("Best of {} runs over {} repeats".format(number, repeat))
for test in (test_find_p, test_split_p, test_re_p):
best_time = min(timeit.repeat(test, number=number, repeat=repeat))
print("{}: {}".format(test.func.__name__, best_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment