Created
October 28, 2014 21:22
-
-
Save jonathaneunice/fed67abca4150cf85d35 to your computer and use it in GitHub Desktop.
This file contains 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
from random import choice, randint | |
import string | |
import time | |
import sys | |
_PY3 = sys.version_info[0] == 3 | |
if _PY3: | |
xrange = range | |
def str_key(length=50, alphabet=string.ascii_letters): | |
return ''.join(choice(alphabet) for _ in xrange(length)) | |
def int_key(min=10, max=99): | |
return randint(min, max) | |
class TimeRun(): | |
def __init__(self): | |
# Only using setUp in order to subclass later | |
# Can also specify tearDown, eachSetUp, and eachTearDown | |
self.size = 160000 | |
self.n = 50 | |
self.strdict = { str_key():int_key() for _ in xrange(self.n) } | |
self.strkeys = [ str_key() for _ in xrange(self.size) ] | |
def str_look(self): | |
d = self.strdict | |
t0 = time.time() | |
for key in self.strkeys: | |
try: | |
d[key] | |
except KeyError: | |
pass | |
return time.time() - t0 | |
def str_look_get(self): | |
d = self.strdict | |
t0 = time.time() | |
for key in self.strkeys: | |
d.get(key, None) | |
return time.time() - t0 | |
if __name__ == '__main__': | |
T = TimeRun() | |
print "try/except:", T.str_look() | |
print "get:", T.str_look_get() | |
""" | |
EXAMPLE RESULTS: | |
$ python dictlookup2.py | |
try/except: 0.125324010849 | |
get: 0.026025056839 | |
$ pypy dictlookup2.py | |
try/except: 0.0264270305634 | |
get: 0.00489616394043 | |
"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment