Created
May 14, 2019 10:26
-
-
Save etienne87/c54ed71be8c8b7eff3f3294bddb0e029 to your computer and use it in GitHub Desktop.
timing_utils.py
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
from __future__ import division | |
import time | |
import numpy as np | |
class Timing: | |
def __init__(self): | |
self.total = 0 | |
self.ncalls = 0 | |
self.nevents = 0 | |
self.last_num = -1 | |
self.first_iter = True | |
def add(self, runtime): | |
self.total += runtime | |
self.ncalls += 1 | |
def add_events(self, nevents): | |
if self.last_num != nevents: | |
self.nevents += nevents | |
self.last_num = nevents | |
def runtime(self): | |
return float(self.total)/self.ncalls | |
def speed(self): | |
avg_events = float(self.nevents) / self.ncalls | |
avg_runtime = self.runtime() | |
return avg_events / avg_runtime * 1e-6 | |
def __repr__(self): | |
wrd = '' | |
wrd += str(self.runtime()) + ', (calls: ' + str(self.ncalls) + ')' | |
return wrd | |
TIMINGS = {} | |
def timefunc(f): | |
def f_timer(*args, **kwargs): | |
global TIMINGS | |
if f.__name__ not in TIMINGS: | |
TIMINGS[f.__name__] = Timing() | |
#result = f(*args, **kwargs) | |
start = time.time() | |
result = f(*args, **kwargs) | |
end = time.time() | |
if len(args) > 1 and isinstance(args[1], np.ndarray) and len(args[1].shape) == 1: | |
nevs = len(args[1]) | |
for k in TIMINGS.keys(): | |
TIMINGS[k].add_events(nevs) | |
TIMINGS[f.__name__].add(end-start) | |
return result | |
return f_timer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
need to add decorator to time your functions (@timefunc)