Skip to content

Instantly share code, notes, and snippets.

@gregreen
Last active May 3, 2017 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregreen/7921bcc1f2c09fdccf570cf520aa942b to your computer and use it in GitHub Desktop.
Save gregreen/7921bcc1f2c09fdccf570cf520aa942b to your computer and use it in GitHub Desktop.
SkyCoord.reshape Speed Test
from __future__ import print_function, division
import timeit
import numpy as np
# First, test how long it takes to reshape a numpy array
repeat = 20
number = 100000
setup = """
import numpy as np
shape = (20,10,3)
s = (shape[0]*shape[1], shape[2])
"""
stmt = """
x = np.random.random(shape)
x.shape = s
"""
t1 = np.percentile(timeit.repeat(setup=setup, stmt=stmt, repeat=repeat, number=number), 5.) / number
stmt = """
x = np.random.random(shape)
"""
t0 = np.percentile(timeit.repeat(setup=setup, stmt=stmt, repeat=repeat, number=number), 5.) / number
print(('numpy.ndarray timings\n'
'=========================\n'
' random: {:.4f} ms\n' +
'random+reshape: {:.4f} ms\n' +
' difference: {:.4f} ms'
).format(1.e3*t0, 1.e3*t1, 1.e3*(t1-t0)))
# On my laptop, I get:
#
# random: 0.0069 ms
# random+reshape: 0.0073 ms
# difference: 0.0004 ms
#
# I think the 0.0004 ms is indistinguishable from noise (e.g., the real time may be much less).
# Next, test how long it takes to reshape a SkyCoord
repeat = 10
number = 50
setup = """
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
shape = (20,10,3)
s = (shape[0]*shape[1], shape[2])
"""
stmt = """
l = np.random.random(shape)
b = np.random.random(shape)
c = SkyCoord(l*u.deg, b*u.deg, frame='galactic')
c2 = c.reshape(s)
"""
t1 = np.percentile(timeit.repeat(setup=setup, stmt=stmt, repeat=repeat, number=number), 5.) / number
stmt = """
l = np.random.random(shape)
b = np.random.random(shape)
c = SkyCoord(l*u.deg, b*u.deg, frame='galactic')
"""
t0 = np.percentile(timeit.repeat(setup=setup, stmt=stmt, repeat=repeat, number=number), 5.) / number
print(('SkyCoord timings\n'
'=========================\n'
' random: {:.4f} ms\n' +
'random+reshape: {:.4f} ms\n' +
' difference: {:.4f} ms'
).format(1.e3*t0, 1.e3*t1, 1.e3*(t1-t0)))
# On my laptop, I get:
#
# random: 15.2013 ms
# random+reshape: 47.2483 ms
# difference: 32.0470 ms
#
# On my laptop, changing the size of the input coordinates from 600 to 6
# does not change the answer, so there appears to be some size-independent
# overhead of about 30 ms in SkyCoord.reshape.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment