Skip to content

Instantly share code, notes, and snippets.

@LyleScott
Last active October 31, 2018 09:52
Show Gist options
  • Save LyleScott/d17e9d314fbe6fc29767d8c5c029c362 to your computer and use it in GitHub Desktop.
Save LyleScott/d17e9d314fbe6fc29767d8c5c029c362 to your computer and use it in GitHub Desktop.
Timers for a few ways to rotate a 2d point around another point in Python
"""
Lyle Scott, III // lyle@ls3.io
Python execution timers for https://gist.github.com/LyleScott/e36e08bfb23b1f87af68c9051f985302
"""
from __future__ import print_function
import timeit
# Setup steps that aren't timed.
setup = """
import math
import numpy as np
theta = math.radians(90)
point = (5, -11)
"""
test = """
def rotate_via_numpy(xy, radians):
x, y = xy
c, s = np.cos(radians), np.sin(radians)
j = np.matrix([[c, s], [-s, c]])
m = np.dot(j, [x, y])
return float(m.T[0]), float(m.T[1])
rotate_via_numpy(point, theta)
"""
print(timeit.timeit(setup=setup, stmt=test, number=1000000))
test = """
def rotate_origin_only(xy, radians):
x, y = xy
xx = x * math.cos(radians) + y * math.sin(radians)
yy = -x * math.sin(radians) + y * math.cos(radians)
return xx, yy
rotate_origin_only(point, theta)
"""
print(timeit.timeit(setup=setup, stmt=test, number=1000000))
test = """
def rotate_around_point_lowperf(point, radians, origin=(0, 0)):
x, y = point
ox, oy = origin
qx = ox + math.cos(radians) * (x - ox) + math.sin(radians) * (y - oy)
qy = oy + -math.sin(radians) * (x - ox) + math.cos(radians) * (y - oy)
return qx, qy
rotate_around_point_lowperf(point, theta)
"""
print(timeit.timeit(setup=setup, stmt=test, number=1000000))
test = """
def rotate_around_point_highperf(xy, radians, origin=(0, 0)):
x, y = xy
offset_x, offset_y = origin
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = math.cos(radians)
sin_rad = math.sin(radians)
qx = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
qy = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return qx, qy
rotate_around_point_highperf(point, theta)
"""
print(timeit.timeit(setup=setup, stmt=test, number=1000000))
"""
Results:
26.5627160072
0.854506015778
1.06204891205
0.86154294014
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment