Created
July 23, 2020 14:42
-
-
Save lordmauve/344797625700aafa15dd5c039e68d7f3 to your computer and use it in GitHub Desktop.
Benchmark script for various vector classes
This file contains 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
"""Benchmarks for vector classes in Python""" | |
from timeit import Timer | |
def timeit(name, stmt): | |
defs = dict( | |
v=v, | |
a=v(1.0, 2.0), | |
b=v(-1.0, -1.0), | |
) | |
loops, time = Timer( | |
setup="c = v(0, 0)", | |
stmt=stmt, | |
globals={**globals(), **defs}, | |
).autorange() | |
dur = time / loops | |
print(f"{name}: {dur * 1e6:0.2f}us per op ({loops} samples)") | |
import vec | |
v = vec.Vector2 | |
print("*** vec ***") | |
timeit("Addition", "a + b") | |
timeit("In-place addition", "c += b") | |
timeit("Dot", "a.dot(b)") | |
timeit("Normalized", "a.normalized()") | |
print() | |
import compiled.vec | |
v = compiled.vec.Vector2 | |
print("*** cythonised vec ***") | |
timeit("Addition", "a + b") | |
timeit("In-place addition", "c += b") | |
timeit("Dot", "a.dot(b)") | |
timeit("Normalized", "a.normalized()") | |
print() | |
import pygame.math | |
v = pygame.math.Vector2 | |
print("*** pygame Vector2 ***") | |
timeit("Addition", "a + b") | |
timeit("In-place addition", "c += b") | |
timeit("Dot", "a.dot(b)") | |
timeit("Normalized", "a.normalize()") | |
print() | |
import numpy as np | |
v = lambda a, b: np.array([a, b], dtype=np.double) | |
hypot = np.hypot | |
print("*** numpy ***") | |
timeit("Addition", "a + b") | |
timeit("In-place addition", "c += b") | |
timeit("Dot", "np.dot(a, b)") | |
timeit("Normalized", "a / hypot(*a)") | |
print() | |
v = lambda *args: args | |
from math import hypot | |
print("*** tuples ***") | |
timeit("Addition", "ax, ay = a; bx, by = b; (ax + bx, ay + by)") | |
timeit("In-place addition", "cx, cy = c; bx, by = b; c = (cx + bx, cy + by)") | |
timeit("Dot", "ax, ay = a; bx, by = b; (ax * bx + ay * by)") | |
timeit("Normalized", "ax, ay = a; mag = hypot(ax, ay); (ax / mag, ay / mag)") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment