If your setup is computationally expensive, use setup_cache. Unlike setup, which runs for every benchmark and every repeat, setup_cache runs only once and caches the result to disk.
There are two ways to use setup_cache:
- Return a data structure: ASV pickles the returned object to disk and passes it as the first argument to the benchmark.
- Save files manually: Save data to the current working directory (managed by ASV) and load it in a standard
setup method.
Attributes:
setup_cache.timeout: You can specify a timeout for the cache calculation by setting the .timeout attribute on the function. If not set, it defaults to the maximum timeout of the benchmarks using it.- Project-wide timeouts can be set via the
default_benchmark_timeout configuration option.
# Example 1: Returning a pickled data structure
class Suite:
def setup_cache(self):
fib = [1, 1]
for i in range(100):
fib.append(fib[-2] + fib[-1])
return fib
def track_fib(self, fib):
return fib[-1]
# Example 2: Explicitly saving files
class Suite:
def setup_cache(self):
with open("test.dat", "wb") as fd:
for i in range(100):
fd.write(f'{i}\n')
def setup(self):
with open("test.dat", "rb") as fd:
self.data = [int(x) for x in fd.readlines()]
def track_numbers(self):
return len(self.data)