Created
October 30, 2009 03:10
-
-
Save fcamel/222080 to your computer and use it in GitHub Desktop.
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
#!/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