Created
January 19, 2018 16:06
-
-
Save pganssle/b83f0a4552e2ae1cf0e35f6676300b9b to your computer and use it in GitHub Desktop.
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
import timeit | |
import operator | |
def time_func(f, N, k=3): | |
"""Basic version of IPython's %timeit magic""" | |
t = min(timeit.timeit(f, number=N) for _ in range(k)) | |
t_per = t / N | |
if t_per < 1e-6: | |
units = 'ns' | |
t_per *= 1e9 | |
elif t_per < 1e-3: | |
units = 'µs' | |
t_per *= 1e6 | |
else: | |
units = 'ms' | |
t_per *= 1e3 | |
print(f'{N} loops, best of {k}: {t_per:0.4} {units}') | |
def xform_by_getter(l, getter): | |
return [getter(k) for k in l] | |
ig = operator.itemgetter(0) | |
igl = lambda x: x[0] | |
l = [(i,) * 5 for i in range(1000)] | |
time_func(lambda: xform_by_getter(l, ig), 5000) | |
# 5000 loops, best of 3: 110.3 µs | |
time_func(lambda: xform_by_getter(l, igl), 5000) | |
# 5000 loops, best of 3: 129.1 µs | |
class ArbGet: | |
def __getitem__(self, idx): | |
return idx * 9 | |
la = [ArbGet() for _ in range(1000)] | |
time_func(lambda: xform_by_getter(la, ig), 5000) | |
# 5000 loops, best of 3: 307.3 µs | |
time_func(lambda: xform_by_getter(la, igl), 5000) | |
# 5000 loops, best of 3: 326.7 µs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment