Skip to content

Instantly share code, notes, and snippets.

@mwhooker
Created January 2, 2014 09:22
Show Gist options
  • Save mwhooker/8216778 to your computer and use it in GitHub Desktop.
Save mwhooker/8216778 to your computer and use it in GitHub Desktop.
from timeit import timeit
def dotest(target_size, number):
setup = "target = [object() for x in xrange(%s)]" % target_size
comprehensions = [
"[id(obj) for obj in target]",
"[obj for obj in target if id(obj) % 2 == 0]"
]
generators = [
"list(id(obj) for obj in target)",
"list(obj for obj in target if id(obj) % 2 == 0)"
]
isetup = "from itertools import imap, ifilter; " + setup
itertools = [
"list(imap(lambda obj: id(obj), target))",
"list(ifilter(lambda obj: id(object()) % 2 == 0, target))"
]
builtins = [
"map(lambda obj: id(obj), target)",
"filter(lambda obj: id(object()) % 2 == 0, target)"
]
print "setup: ", setup
for c in comprehensions + builtins + generators:
print c
print timeit(c, setup, number=number)
print "setup: ", isetup
for i in itertools:
print i
print timeit(i, isetup, number=number)
if __name__ == '__main__':
print "test A"
dotest(100, 1000000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment