Skip to content

Instantly share code, notes, and snippets.

@Utumno
Last active October 13, 2016 10:22
Show Gist options
  • Save Utumno/f3d25e0fe4bd0f43ceb9178a60181a53 to your computer and use it in GitHub Desktop.
Save Utumno/f3d25e0fe4bd0f43ceb9178a60181a53 to your computer and use it in GitHub Desktop.
import timeit
repeat = 7
numbers = 1000
# repeat = numbers = 1 # uncomment to count cmp and equal calls
def time(statement, _setup=None):
print min(
timeit.Timer(statement, setup=_setup or setup).repeat(repeat, numbers))
imports = """
import random
import string
from operator import itemgetter
random.seed('slartibartfast')
d={}"""
print "***** STRINGS"
setup = imports + """
for i in range(1000):
d[''.join(random.choice(string.ascii_uppercase) for _ in range(16))] = 0
"""
time('for k,v in sorted(d.iteritems()): pass')
time('for k,v in sorted(d.iteritems(),key=lambda x: x[0]): pass')
time('for k,v in sorted(d.iteritems(),key=itemgetter(0)): pass')
print "***** INTS"
setup = imports + """
for i in range(1000):
d[random.randint(0, 1000)] = 0
"""
time('for k,v in sorted(d.iteritems()): pass')
time('for k,v in sorted(d.iteritems(), key=lambda x: x[0]): pass')
time('for k,v in sorted(d.iteritems(), key=itemgetter(0)): pass')
print "***** OBJECTS"
# repeat = numbers = 1 # uncomment to count cmp and equal calls
setup = imports + """
class A(object):
eq_calls = 0
cmp_calls = 0
def __init__(self):
self.s = ''.join(random.choice(string.ascii_uppercase) for _ in
range(16))
def __hash__(self): return hash(self.s)
def __eq__(self, other):
# self.__class__.eq_calls += 1
return self.s == other.s
def __ne__(self, other): return self.s != other.s
def __cmp__(self, other):
# self.__class__.cmp_calls += 1
return cmp(self.s ,other.s)
for i in range(1000):
d[A()] = 0
"""
time("""for k,v in sorted(d.iteritems()): pass
# print A.eq_calls
# print A.cmp_calls""")
time("""for k,v in sorted(d.iteritems(),key=lambda x: x[0]): pass
# print A.eq_calls
# print A.cmp_calls""")
time('for k,v in sorted(d.iteritems(),key=itemgetter(0)): pass')
print "***** BONUS range vs xrange and inlining length"
time('for _ in range(len(li)): pass', _setup="li=[x for x in xrange(100000)]")
time("""k=len(li)
for _ in range(k): pass""", _setup="li=[x for x in xrange(100000)]")
time('for _ in xrange(len(li)): pass', _setup="li=[x for x in xrange(100000)]")
time("""k=len(li)
for _ in xrange(k): pass""", _setup="li=[x for x in xrange(100000)]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment