Created
November 1, 2017 13:14
-
-
Save kjaanson/2881393d4358bbf2bf19263a4e60f0de to your computer and use it in GitHub Desktop.
Benchmarking and timing decorators for python
This file contains 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
import time | |
def timeit(value_dict=None, print_values=True): | |
"""Decorator for timing functions with different parameters. | |
Arguments: | |
value_dict - dict where to save the timings, uses function args tupple as key | |
print_values - boolean for printing timings to std out | |
Usage: | |
``` | |
log_time_dict={} | |
@timeit(value_dict=log_time_dict) | |
def kala(sleep): | |
time.sleep(sleep) | |
kala(1,koll=1) | |
kala(2,koll=1) | |
kala(3,koll=1) | |
log_time_dict | |
``` | |
""" | |
def timeit_dec(method): | |
def timed(*args, **kw): | |
ts = time.time() | |
result = method(*args, **kw) | |
te = time.time() | |
if isinstance(value_dict, dict): | |
value_dict[args] = int((te - ts) * 1000) | |
if print_values: | |
print(f'{method.__name__} {args} {(te - ts) * 1000:2.2f} ms') | |
return result | |
return timed | |
return timeit_dec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment