Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python3
from math import hypot
from numbers import Real
from ppb_vector import Vector2
from timeit import timeit
class VectorBench(Vector2):
def computed_length(self) -> Real:
return hypot(self.x, self.y)
if __name__ == "__main__":
for reps in [1, 5, 10, 25, 50, 100]:
setup = 'v = VectorBench(0.1234, 5.6789)'
memoized = timeit(f'for _ in range({reps}): v.length', setup, globals=globals())
computed = timeit(f'for _ in range({reps}): v.computed_length', setup, globals=globals())
print(f"{reps} successive length computations")
print(f"\tMemoized: {memoized}")
print(f"\tComputed: {computed}")
print(f"\tSpeedup: {100 * (computed/memoized -1)}%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.