Skip to content

Instantly share code, notes, and snippets.

@kjaanson
Created November 1, 2017 13:14
Show Gist options
  • Save kjaanson/2881393d4358bbf2bf19263a4e60f0de to your computer and use it in GitHub Desktop.
Save kjaanson/2881393d4358bbf2bf19263a4e60f0de to your computer and use it in GitHub Desktop.
Benchmarking and timing decorators for python
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