1from atexit
import register
as registerExit
5def timeFunc(func, accuracy=5):
6 """ A function decorator that prints how long it takes for a function to run """
7 def wrap(*params, **kwparams):
12 returns = func(*params, **kwparams)
16 elapsed_time = round(t2 - t, accuracy)
20 timingData[name] += (elapsed_time,)
22 timingData[name] = (elapsed_time,)
26 print(f
'{name:<12} took {elapsed_time:.{accuracy}f} seconds to run.')
31def _printTimingData(accuracy=5):
32 """ I realized *after* I wrote this that this is a essentially profiler. Oops. """
37 maxName = len(max(timingData.keys(), key=len))
38 maxNum = len(str(len(max(timingData.values(), key=
lambda x: len(str(len(x)))))))
39 for name, times
in reversed(sorted(timingData.items(), key=
lambda x: sum(x[1]))):
40 print(f
'{name:<{maxName}} was called {len(times):<{maxNum}} times taking {sum(times)/len(times):.{accuracy}f} seconds on average for a total of {sum(times):.{accuracy}f} seconds.')
41registerExit(_printTimingData)
44 """ A class to use with a with statement like so:
47 It will then
print how long the enclosed code took to run.
49 def __init__(self, name, accuracy=5):
54 self.
t = process_time()
56 def __exit__(self, *args):
59 elapsed_time = round(t2 - self.
t, self.
accuracy)
60 print(self.
name,
' ' * (15 - len(self.
name)),
'took', f
'{elapsed_time:.{self.accuracy}f}',
'\ttime to run.')
62def psleep(seconds, func, rtn=True):
63 """ Process sleep: run func in a while loop for a specified amount of time """
A class to use with a with statement like so: with getTime('sleep'): time.sleep(10) It will then prin...