Cope 2.5.0
My personal "standard library" of all the generally useful code I've written for various projects over the years
Loading...
Searching...
No Matches
timing.py
1from atexit import register as registerExit
2# TODO: reevaluate all these to use the timeit package instead
3
4timingData = {}
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):
8 global timingData
9
10 t = process_time()
11
12 returns = func(*params, **kwparams)
13
14 t2 = process_time()
15
16 elapsed_time = round(t2 - t, accuracy)
17 name = func.__name__
18
19 try:
20 timingData[name] += (elapsed_time,)
21 except KeyError:
22 timingData[name] = (elapsed_time,)
23
24 _printDebugCount()
25 # print(name, ' ' * (10 - len(name)), 'took', elapsed_time if elapsed_time >= 0.00001 else 0.00000, '\ttime to run.')
26 print(f'{name:<12} took {elapsed_time:.{accuracy}f} seconds to run.')
27 # ' ' * (15 - len(name)),
28 return returns
29 return wrap
30
31def _printTimingData(accuracy=5):
32 """ I realized *after* I wrote this that this is a essentially profiler. Oops. """
33 global timingData
34 if len(timingData):
35 print()
36
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)
42
43class getTime:
44 """ A class to use with a with statement like so:
45 with getTime('sleep'):
46 time.sleep(10)
47 It will then print how long the enclosed code took to run.
48 """
49 def __init__(self, name, accuracy=5):
50 self.name = name
51 self.accuracy = accuracy
52
53 def __enter__(self):
54 self.t = process_time()
55
56 def __exit__(self, *args):
57 # args is completely useless, not sure why it's there.
58 t2 = process_time()
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.')
61
62def psleep(seconds, func, rtn=True):
63 """ Process sleep: run func in a while loop for a specified amount of time """
64 end = now()
65 while now() < end:
66 func()
A class to use with a with statement like so: with getTime('sleep'): time.sleep(10) It will then prin...
Definition: timing.py:43