Skip to content

Instantly share code, notes, and snippets.

@maedoc
Created February 8, 2014 08:50
Show Gist options
  • Select an option

  • Save maedoc/8878751 to your computer and use it in GitHub Desktop.

Select an option

Save maedoc/8878751 to your computer and use it in GitHub Desktop.
Benchmark class generator vs function generator
# coding: utf-8
import time
import operator as op
import numpy as np
# equivalent generators
def foo(n):
i = -1
while i < n:
i += 1
yield i
class Foo(object):
def __iter__(self):
return self
def __init__(self, n):
self.i = -1
self.n = n
def next(self):
if self.i < self.n:
self.i += 1
return self.i
else:
raise StopIteration
def tic(n):
t0 = time.time()
reduce(op.add, foo(n))
return time.time() - t0
def Tic(n):
t0 = time.time()
reduce(op.add, Foo(n))
return time.time() - t0
# measure each
ns = (10**(np.random.rand(5000)*4 + 1)).astype(int)
x, y = map(tic, ns), map(Tic, ns)
# compute ratio
yox = np.array(y)/np.array(x)
yox = yox[np.isfinite(yox)]
print np.median(yox)
# -> 1.58 on my machine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment