Skip to content

Instantly share code, notes, and snippets.

@bnlucas
Last active August 29, 2015 14:23
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 bnlucas/dcc77c788e8823916ce3 to your computer and use it in GitHub Desktop.
Save bnlucas/dcc77c788e8823916ce3 to your computer and use it in GitHub Desktop.
'''
def test1(stop=100):
for i in range(stop):
pass
def test2(stop=100):
for i in xrange(stop):
pass
compare = Compare('Testing the use of range and xrange.')
compare.add(test1, 10**5)
compare.add(test2, 10**5)
compare.run(1000, 100)
Outputs:
--------------------------------------------------------------------------------
Testing the use of range and xrange.
comparing best 100 of 1000 loops.
--------------------------------------------------------------------------------
test2 @ 0.002969923s
test1 @ 0.004339960s
--------------------------------------------------------------------------------
'''
class Compare(object):
def __init__(self, title=None):
self.title = title
self.methods = []
def benchmark(self, loops, best_of, method, *args, **kwargs):
call = method.__name__
runs = []
for i in xrange(loops):
t1 = time()
method(*args, **kwargs)
t2 = time()
runs.append(t2 - t1)
return (call, sum(sorted(runs)[:best_of - 1]) / best_of)
def add(self, method, *args, **kwargs):
self.methods.append((method, (args, kwargs)))
def run(self, loops=10, best_of=3):
if loops < best_of:
best_of = loops
runs = []
for method in self.methods:
benchmark = self.benchmark(loops, best_of, method[0],
*method[1][0], **method[1][1])
runs.append(benchmark)
runs.sort(key=operator.itemgetter(1))
print '-' * 80
if self.title:
print ' ' + self.title
print ''
print ' comparing best {} of {} loops.'.format(best_of, loops)
print '-' * 80
for i in runs:
print ' {: <56} @ {: >18.9f}s '.format(i[0], i[1])
print '-' * 80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment