Skip to content
This repository was archived by the owner on Jan 22, 2023. It is now read-only.

Commit 1d4f15c

Browse files
author
Alex Conley
committed
Speedup of initialization for cosmology objects
* Speed up initialization by about a factor of 100 by pre-computing some unit conversion quantities. It turns out this was the dominant cost, particularly the call to const.G.cgs. * import astropy.cosmology time falls by about 50% * Passes all unit tests * Closes astropy/astropy#2479 (sorta; some more sophisticated options were also discussed for that, and this just does the simple bit).
1 parent 353670c commit 1d4f15c

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

‎cosmology/core.py‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,22 @@
3636
# Mpc in km
3737
Mpc_km = (1 * u.Mpc).to(u.km)
3838

39+
# Some conversion constants -- useful to compute them once here
40+
# and reuse in the initialization rather than have every object do them
41+
# Note that the call to const.G.cgs.value is actually extremely expensive,
42+
# so it is very useful to preload that one. In fact, we skip using
43+
# units for that as well, which is suprisingly expensive, because
44+
# the conversion from G in mks to G in cgs is a rather trivial one.
45+
# This assumes that constants will always return mks by default --
46+
# if this is made faster for simple cases like this, it should
47+
# be changed to just using const.G.cgs.value
48+
H0units_to_invs = (u.km / (u.s * u.Mpc)).to(1.0 / u.s)
49+
sec_to_Gyr = u.s.to(u.Gyr)
50+
critdens_const = 3. / (8. * pi * const.G.value * 1000) # cgs const in critdens
51+
3952
arcsec_in_radians = 1 / 3600. * pi / 180
4053
arcmin_in_radians = 1 / 60. * pi / 180
4154

42-
4355
# Radiation parameter over c^2 in cgs
4456
a_B_c2 = 4 * const.sigma_sb.cgs.value / const.c.cgs.value ** 3
4557

@@ -132,14 +144,14 @@ def __init__(self, H0, Om0, Ode0, Tcmb0=2.725, Neff=3.04,
132144
self._h = self._H0.value / 100.
133145
# Hubble distance
134146
self._hubble_distance = (const.c / self._H0).to(u.Mpc)
135-
# H0 in s^-1
136-
H0_s = self._H0.to(1.0 / u.s)
137-
# Hubble time
138-
self._hubble_time = (1. / H0_s).to(u.Gyr)
147+
# H0 in s^-1; don't use units for speed
148+
H0_s = self._H0.value * H0units_to_invs
149+
# Hubble time; again, avoiding units package for speed
150+
self._hubble_time = u.Quantity(sec_to_Gyr / H0_s, u.Gyr)
139151

140152
# critical density at z=0 (grams per cubic cm)
141-
self._critical_density0 = (3. * H0_s ** 2 /
142-
(8. * pi * const.G.cgs)).cgs
153+
cd0value = critdens_const * H0_s ** 2
154+
self._critical_density0 = u.Quantity(cd0value, u.g / u.cm ** 3)
143155

144156
# Load up neutrino masses.
145157
self._nneutrinos = int(floor(self._Neff)) # In Py2.x, floor is floating

0 commit comments

Comments
 (0)