Use cache for computation Examples -------- >>> cache = Cache(1e9) # doctest: +SKIP The cache can be used locally as a context manager around ``compute`` or ``get`` calls: >>> with cache: # doctest: +SKIP ... result = x.compute() You can also register a cac
| 10 | |
| 11 | |
| 12 | class Cache(Callback): |
| 13 | """Use cache for computation |
| 14 | |
| 15 | Examples |
| 16 | -------- |
| 17 | |
| 18 | >>> cache = Cache(1e9) # doctest: +SKIP |
| 19 | |
| 20 | The cache can be used locally as a context manager around ``compute`` or |
| 21 | ``get`` calls: |
| 22 | |
| 23 | >>> with cache: # doctest: +SKIP |
| 24 | ... result = x.compute() |
| 25 | |
| 26 | You can also register a cache globally, so that it works for all |
| 27 | computations: |
| 28 | |
| 29 | >>> cache.register() # doctest: +SKIP |
| 30 | >>> cache.unregister() # doctest: +SKIP |
| 31 | """ |
| 32 | |
| 33 | def __init__(self, cache, *args, **kwargs): |
| 34 | try: |
| 35 | import cachey |
| 36 | except ImportError as ex: |
| 37 | raise type(ex)(f'Cache requires cachey, "{ex}" problem importing') from ex |
| 38 | self._nbytes = cachey.nbytes |
| 39 | if isinstance(cache, Number): |
| 40 | cache = cachey.Cache(cache, *args, **kwargs) |
| 41 | else: |
| 42 | assert not args and not kwargs |
| 43 | self.cache = cache |
| 44 | self.starttimes = dict() |
| 45 | |
| 46 | def _start(self, dsk): |
| 47 | self.durations = dict() |
| 48 | overlap = set(dsk) & set(self.cache.data) |
| 49 | for key in overlap: |
| 50 | dsk[key] = self.cache.data[key] |
| 51 | |
| 52 | def _pretask(self, key, dsk, state): |
| 53 | self.starttimes[key] = default_timer() |
| 54 | |
| 55 | def _posttask(self, key, value, dsk, state, id): |
| 56 | duration = default_timer() - self.starttimes[key] |
| 57 | deps = state["dependencies"][key] |
| 58 | if deps: |
| 59 | duration += max(self.durations.get(k, 0) for k in deps) |
| 60 | self.durations[key] = duration |
| 61 | nb = self._nbytes(value) + overhead + sys.getsizeof(key) * 4 |
| 62 | self.cache.put(key, value, cost=duration / nb / 1e9, nbytes=nb) |
| 63 | |
| 64 | def _finish(self, dsk, state, errored): |
| 65 | self.starttimes.clear() |
| 66 | self.durations.clear() |
no outgoing calls
searching dependent graphs…