Skip to content

Instantly share code, notes, and snippets.

@dawranliou
Last active February 19, 2017 01:15
Show Gist options
  • Save dawranliou/36926def2509f7b0cef21fcc0c1d9bee to your computer and use it in GitHub Desktop.
Save dawranliou/36926def2509f7b0cef21fcc0c1d9bee to your computer and use it in GitHub Desktop.
from time import perf_counter
from array import array
from contextlib import contextmanager
@contextmanager
def timing(label: str):
t0 = perf_counter()
yield lambda: (label, t1 - t0)
t1 = perf_counter()
with timing('Array tests') as total:
with timing('Array creation innermul') as inner:
x = array('d', [0] * 1000000)
with timing('Array creation outermul') as outer:
x = array('d', [0]) * 1000000
print('Total [%s]: %.6f s' % total())
print(' Timing [%s]: %.6f s' % inner())
print(' Timing [%s]: %.6f s' % outer())
# Total [Array tests]: 0.064896 s
# Timing [Array creation innermul]: 0.064195 s
# Timing [Array creation outermul]: 0.000659 s
def mult_function_generator(max):
for i in range(max):
yield lambda x: x * i
mult_functions = list(mult_function_generator(3))
print([func(3) for func in mult_functions])
# Oh crap, it's [6, 6, 6], not [0, 3, 6]
mult_functions = mult_function_generator(3)
mult_zero = next(mult_functions)
mult_zero
# <function ...>
mult_zero.__closure__
# (<cell at 0x..., int object at 0x...>,)
cell_zero = mult_zero.__closure__[0]
cell_zero.cell_contents
# 0
mult_one = next(mult_functions)
cell_one = mult_one.__closure__[0]
cell_one.cell_contents
# 1
# So far so good. But...
cell_zero.cell_contents
# 1
# Crap!
cell_zero is cell_one
# True
# Okay fine
def mult_function_generator_1(max):
for i in range(max):
yield (lambda i: lambda x: x * i)(i)
def mult_function_generator_2(max):
for i in range(max):
yield functools.partial(lambda x, i: x * i, i=i)
def mult_function_generator_3(max):
for i in range(max):
yield lambda x, i=i: x * i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment