Skip to content

Commit e7d94e0

Browse files
authored
Merge pull request #1508 from pllim/add-timer
Move timer functions from astropy
2 parents fca9945 + c50bbc4 commit e7d94e0

File tree

7 files changed

+471
-4
lines changed

7 files changed

+471
-4
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ ukidss
150150
utils
151151
^^^^^
152152

153+
- Added timer functions. [#1508]
154+
153155
vamdc
154156
^^^^^
155157

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Licensed under a 3-clause BSD style license - see LICENSE.rst
2+
"""Test `astroquery.utils.timer`.
3+
4+
.. note::
5+
6+
The tests only compare rough estimates as
7+
performance is machine-dependent.
8+
9+
"""
10+
11+
# STDLIB
12+
import time
13+
14+
# THIRD-PARTY
15+
import pytest
16+
import numpy as np
17+
from astropy.utils.exceptions import AstropyUserWarning
18+
from astropy.modeling.fitting import ModelsError
19+
20+
# LOCAL
21+
from ..timer import RunTimePredictor
22+
23+
24+
def func_to_time(x):
25+
"""This sleeps for y seconds for use with timing tests.
26+
27+
.. math::
28+
29+
y = 5 * x - 10
30+
31+
"""
32+
y = 5.0 * np.asarray(x) - 10
33+
time.sleep(y)
34+
return y
35+
36+
37+
def test_timer():
38+
"""Test function timer."""
39+
p = RunTimePredictor(func_to_time)
40+
41+
# --- These must run before data points are introduced. ---
42+
43+
with pytest.raises(ValueError):
44+
p.do_fit()
45+
46+
with pytest.raises(RuntimeError):
47+
p.predict_time(100)
48+
49+
# --- These must run next to set up data points. ---
50+
51+
with pytest.warns(AstropyUserWarning, match="ufunc 'multiply' did not "
52+
"contain a loop with signature matching types"):
53+
p.time_func([2.02, 2.04, 2.1, 'a', 2.3])
54+
p.time_func(2.2) # Test OrderedDict
55+
56+
assert p._funcname == 'func_to_time'
57+
assert p._cache_bad == ['a']
58+
59+
k = list(p.results.keys())
60+
v = list(p.results.values())
61+
np.testing.assert_array_equal(k, [2.02, 2.04, 2.1, 2.3, 2.2])
62+
np.testing.assert_allclose(v, [0.1, 0.2, 0.5, 1.5, 1.0])
63+
64+
# --- These should only run once baseline is established. ---
65+
66+
with pytest.raises(ModelsError):
67+
a = p.do_fit(model='foo')
68+
69+
with pytest.raises(ModelsError):
70+
a = p.do_fit(fitter='foo')
71+
72+
a = p.do_fit()
73+
74+
assert p._power == 1
75+
76+
# Perfect slope is 5, with 10% uncertainty
77+
assert 4.5 <= a[1] <= 5.5
78+
79+
# Perfect intercept is -10, with 1-sec uncertainty
80+
assert -11 <= a[0] <= -9
81+
82+
# --- These should only run once fitting is completed. ---
83+
84+
# Perfect answer is 490, with 10% uncertainty
85+
t = p.predict_time(100)
86+
assert 441 <= t <= 539
87+
88+
# Repeated call to access cached run time
89+
t2 = p.predict_time(100)
90+
assert t == t2

0 commit comments

Comments
 (0)