Skip to content

Instantly share code, notes, and snippets.

@cpdean
Created September 9, 2011 16:53
Show Gist options
  • Save cpdean/1206726 to your computer and use it in GitHub Desktop.
Save cpdean/1206726 to your computer and use it in GitHub Desktop.
python optimizations
import time
import itertools
import hashlib
def regular_for_loop(bound):
_md5 = hashlib.md5()
for i in itertools.repeat("foo", bound):
_md5.update(i)
def regular_for_loop_without_dot(bound):
_md5 = hashlib.md5()
update = _md5.update
for i in itertools.repeat("foo", bound):
update(i)
def using_imap(bound):
_md5 = hashlib.md5()
itertools.imap(_md5.update, itertools.repeat("foo", bound))
def using_imap_and_any(bound):
_md5 = hashlib.md5()
any(itertools.imap(_md5.update, itertools.repeat("foo", bound)))
def using_imap_and_any_without_dot(bound):
_md5 = hashlib.md5()
update = _md5.update
any(itertools.imap(update, itertools.repeat("foo", bound)))
def test(f,bound,number_of_runs):
total_time = 0
for i in range(number_of_runs):
total_time += single_time(f,bound)
return (total_time, f.__name__)
def single_time(f,bound):
time1 = time.time()
f(bound)
return time.time()-time1
bound = 10**5
tests = []
tests.append(test(regular_for_loop,bound,10))
tests.append(test(regular_for_loop_without_dot,bound,10))
tests.append(test(using_imap_and_any,bound,10))
tests.append(test(using_imap,bound,10))
tests.append(test(using_imap_and_any_without_dot,bound,10))
for time,name in sorted(tests):
print time, "for", name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment