Created
February 8, 2014 08:50
-
-
Save maedoc/8878751 to your computer and use it in GitHub Desktop.
Benchmark class generator vs function generator
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
| # 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