Skip to content

Instantly share code, notes, and snippets.

@fcamel
Created October 30, 2009 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcamel/222080 to your computer and use it in GitHub Desktop.
Save fcamel/222080 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# demonstrate built-in functions' efficiency.
import timeit
import random
# prepare test data
numbers = range(2)
a = []
for n in numbers:
a = [n] * 10000
random.shuffle(a)
def test():
c = {}
for x in a:
c[x] = c.get(x, 0) + 1
def test2():
c = {}
for n in numbers:
c[n] = 0
for x in a:
c[x] += 1
def test3():
c = {}
for n in numbers:
c[n] = a.count(n)
if __name__=='__main__':
t = timeit.Timer("test()", "from __main__ import test")
print 'test', t.timeit(number=1000)
t = timeit.Timer("test2()", "from __main__ import test2")
print 'test2', t.timeit(number=1000)
t = timeit.Timer("test3()", "from __main__ import test3")
print 'test3', t.timeit(number=1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment