Debian Codegraph @

astropy_healpix/bench.py

raw
1 # Licensed under a 3-clause BSD style license - see LICENSE.rst
2 """Benchmarks for this package.
3
4 To run all benchmarks and print a report to the console::
5
6 python -m healpix.bench
7
8 You can also run the benchmarks first, save the results dict
9 to disk as a JSON file (or share it with others) and then
10 print the results later, or compare them with other results.
11
12 We should now that this is not very comprehensive / flexible.
13
14 If your application depends on performance of HEALPix computations,
15 you should write benchmarks with cases relevant for that application
16 and check if HEALPix computations are really the bottleneck and if
17 this package is fast enough for you or not.
18 """
19
20 import timeit
21
22 from astropy.table import Table
23
24 # NOTE: If healpy is installed, we use it in the benchmarks, but healpy is not
25 # a formal dependency of astropy-healpix.
26 try:
27 import healpy as hp # noqa
28 except ImportError:
29 HEALPY_INSTALLED = False
30 else:
31 HEALPY_INSTALLED = True
32
33
34 # Copied from https://github.com/kwgoodman/bottleneck/blob/master/bottleneck/benchmark/autotimeit.py
35 def autotimeit(stmt, setup='pass', repeat=3, mintime=0.2):
36 timer = timeit.Timer(stmt, setup)
37 number, time1 = autoscaler(timer, mintime)
38 time2 = timer.repeat(repeat=repeat - 1, number=number)
39 return min(time2 + [time1]) / number
40
41
42 # Copied from https://github.com/kwgoodman/bottleneck/blob/master/bottleneck/benchmark/autotimeit.py
43 def autoscaler(timer, mintime):
44 number = 1
45 for i in range(12):
46 time = timer.timeit(number)
47 if time > mintime:
48 return number, time
49 number *= 10
50 raise RuntimeError('function is too fast to test')
51
52
53 def get_import(package, function):
54 if package == 'astropy_healpix':
55 return f'from astropy_healpix.healpy import {function}'
56 else:
57 return f'from healpy import {function}'
58
59
60 def bench_pix2ang(size=None, nside=None, nest=None, package=None, fast=False):
61 setup = '\n'.join([
62 get_import(package, 'pix2ang'),
63 'import numpy as np',
64 f'nside={nside}',
65 f'ipix=(np.random.random({size}) * 12 * nside ** 2).astype(np.int64)',
66 f'nest={nest}'])
67
68 stmt = 'pix2ang(nside, ipix, nest)'
69
70 return autotimeit(stmt=stmt, setup=setup, repeat=1, mintime=0 if fast else 0.1)
71
72
73 def bench_ang2pix(size=None, nside=None, nest=None, package=None, fast=False):
74 setup = '\n'.join([
75 get_import(package, 'ang2pix'),
76 'import numpy as np',
77 f'nside={nside}',
78 f'lon=360 * np.random.random({size})',
79 f'lat=180 * np.random.random({size}) - 90',
80 f'nest={nest}'])
81
82 stmt = 'ang2pix(nside, lon, lat, nest, lonlat=True)'
83
84 return autotimeit(stmt=stmt, setup=setup, repeat=1, mintime=0 if fast else 0.1)
85
86
87 def bench_nest2ring(size=None, nside=None, package=None, fast=False):
88 setup = '\n'.join([
89 get_import(package, 'nest2ring'),
90 'import numpy as np',
91 f'nside={nside}',
92 f'ipix=(np.random.random({size}) * 12 * nside ** 2).astype(np.int64)'])
93
94 stmt = 'nest2ring(nside, ipix)'
95
96 return autotimeit(stmt=stmt, setup=setup, repeat=1, mintime=0 if fast else 0.1)
97
98
99 def bench_ring2nest(size=None, nside=None, package=None, fast=False):
100 setup = '\n'.join([
101 get_import(package, 'ring2nest'),
102 'import numpy as np',
103 f'nside={nside}',
104 f'ipix=(np.random.random({size}) * 12 * nside ** 2).astype(np.int64)'])
105
106 stmt = 'ring2nest(nside, ipix)'
107
108 return autotimeit(stmt=stmt, setup=setup, repeat=1, mintime=0 if fast else 0.1)
109
110
111 def bench_get_interp_weights(size=None, nside=None, nest=None, package=None, fast=False):
112 setup = '\n'.join([
113 get_import(package, 'get_interp_weights'),
114 'import numpy as np',
115 f'nside={nside}',
116 f'lon=360 * np.random.random({size})',
117 f'lat=180 * np.random.random({size}) - 90',
118 f'nest={nest}'])
119
120 stmt = 'get_interp_weights(nside, lon, lat, nest=nest, lonlat=True)'
121
122 return autotimeit(stmt=stmt, setup=setup, repeat=1, mintime=0 if fast else 0.1)
123
124
125 def run_single(name, benchmark, fast=False, **kwargs):
126
127 time_self = benchmark(package='astropy_healpix', fast=fast, **kwargs)
128 results_single = dict(function=name, time_self=time_self, **kwargs)
129
130 if HEALPY_INSTALLED:
131 time_healpy = bench_ang2pix(package='healpy', fast=fast, **kwargs)
132 results_single['time_healpy'] = time_healpy
133
134 return results_single
135
136
137 def bench_run(fast=False):
138 """Run all benchmarks. Return results as a dict."""
139 results = []
140
141 if fast:
142 SIZES = [10, 1_000, 100_000]
143 else:
144 SIZES = [10, 1_000, 1_000_000]
145
146 for nest in [True, False]:
147 for size in SIZES:
148 for nside in [1, 128]:
149 results.append(run_single('pix2ang', bench_pix2ang, fast=fast,
150 size=size, nside=nside, nest=nest))
151
152 for nest in [True, False]:
153 for size in SIZES:
154 for nside in [1, 128]:
155 results.append(run_single('ang2pix', bench_ang2pix, fast=fast,
156 size=size, nside=nside, nest=nest))
157
158 for size in SIZES:
159 for nside in [1, 128]:
160 results.append(run_single('nest2ring', bench_nest2ring, fast=fast,
161 size=size, nside=nside))
162
163 for size in SIZES:
164 for nside in [1, 128]:
165 results.append(run_single('ring2nest', bench_ring2nest, fast=fast,
166 size=size, nside=nside))
167
168 for nest in [True, False]:
169 for size in SIZES:
170 for nside in [1, 128]:
171 results.append(run_single('get_interp_weights', bench_get_interp_weights,
172 fast=fast, size=size,
173 nside=nside, nest=nest))
174
175 return results
176
177
178 def bench_report(results):
179 """Print a report for given benchmark results to the console."""
180
181 table = Table(names=['function', 'nest', 'nside', 'size',
182 'time_healpy', 'time_self', 'ratio'],
183 dtype=['S20', bool, int, int, float, float, float], masked=True)
184 for row in results:
185 table.add_row(row)
186
187 table['time_self'].format = '10.7f'
188
189 if HEALPY_INSTALLED:
190 table['ratio'] = table['time_self'] / table['time_healpy']
191 table['time_healpy'].format = '10.7f'
192 table['ratio'].format = '7.2f'
193
194 table.pprint(max_lines=-1)
195
196
197 def main(fast=False):
198 """Run all benchmarks and print report to the console."""
199 print('Running benchmarks...\n')
200 results = bench_run(fast=fast)
201 bench_report(results)
202
203
204 if __name__ == '__main__':
205 main()