|
| 1 | +""" |
| 2 | +A dummy script which could run much faster. |
| 3 | +
|
| 4 | +Try to profile it, find bad design and correct it! |
| 5 | +
|
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import numpy as np |
| 10 | +from itertools import product |
| 11 | +from collections import namedtuple |
| 12 | +from contexttimer import timer |
| 13 | + |
| 14 | + |
| 15 | +# will be modified, this is is not thread safe! |
| 16 | +cache = namedtuple('keys', 'values') |
| 17 | +cache.keys = [] |
| 18 | +cache.values = [] |
| 19 | + |
| 20 | + |
| 21 | +def read_wind_speed(time, location_x, location_y): |
| 22 | + """Read wind speed value at location x/y and time from fancy database.""" |
| 23 | + key = time, location_x, location_y |
| 24 | + if key in cache.keys: |
| 25 | + idx = cache.keys.index(key) |
| 26 | + return cache.values[idx] |
| 27 | + |
| 28 | + # imagine that this is downloaded from some database: |
| 29 | + value = np.random.random() |
| 30 | + |
| 31 | + # cache it for next time! |
| 32 | + cache.keys.append(key) |
| 33 | + cache.values.append(value) |
| 34 | + |
| 35 | + return value |
| 36 | + |
| 37 | + |
| 38 | +@timer() |
| 39 | +def main(): |
| 40 | + times = np.arange(100) |
| 41 | + locations_x = np.arange(15) |
| 42 | + locations_y = np.arange(18) |
| 43 | + |
| 44 | + values = [read_wind_speed(t, x, y) |
| 45 | + for t, x, y in product(times, locations_x, locations_y)] |
| 46 | + |
| 47 | + print(sum(values) / len(values)) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + logging.basicConfig(level=logging.INFO) |
| 52 | + main() |
0 commit comments