Created
December 13, 2017 18:11
-
-
Save phrz/4f60187fbc68a9e49ac79902328a9a72 to your computer and use it in GitHub Desktop.
Some snippets for testing performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # duration_string(seconds) | |
| # takes a float of seconds and | |
| # returns a formatted unit string | |
| # (microseconds up to years) | |
| # | |
| # with timer(): | |
| # a context that prints the time | |
| # of its inner block | |
| # | |
| # @benchmark() or @benchmark(iterations) | |
| # turns a function into a repeated | |
| # benchmark that prints mean | |
| # and std. deviation of runtimes at | |
| # end (default 10 iterations) | |
| def duration_string(seconds): | |
| if seconds < 1e-3: | |
| return f'{seconds*1e6:.2f}µs' | |
| elif seconds < 1: | |
| return f'{seconds*1e3:.2f}ms' | |
| elif seconds < 80: | |
| return f'{seconds:.3f}s' | |
| elif seconds < 60*60: # seconds per hour | |
| return f'{seconds/60:.2f}mn' | |
| elif seconds < 60*60*24*3: # seconds per 3 days | |
| return f'{seconds/(60*60):.2f}h' | |
| elif seconds < 60*60*24*365: # seconds per year-ish | |
| return f'{seconds/(60*60*24):.1f}d' | |
| else: | |
| return f'{seconds/(60*60*24*365):,.0f}yr' | |
| from time import time | |
| class timer: | |
| def __init__(self): | |
| pass | |
| def __enter__(self): | |
| self.timer = time() | |
| def __exit__(self, type, value, traceback): | |
| self.timer = time() - self.timer | |
| print('Time: ',end='') | |
| print(duration_string(self.timer)) | |
| # A simple decorator takes a function and | |
| # returns a function. A decorator with an | |
| # argument takes just the argument and | |
| # returns a simple decorator. | |
| import numpy as np | |
| def benchmark(iterations: int = 10): | |
| def benchmark_decorator(function: callable): | |
| def decorated(*args, **kwargs): | |
| times = [] | |
| for _ in range(iterations): | |
| t = time() | |
| function(*args, **kwargs) | |
| t = time() - t | |
| times.append(t) | |
| print(f'{iterations} iterations') | |
| print(f'Mean: {duration_string(np.mean(times))}') | |
| print(f' Std: {duration_string(np.std(times))}') | |
| return decorated | |
| return benchmark_decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment