-
Notifications
You must be signed in to change notification settings - Fork 0
/
timethis.py
61 lines (44 loc) · 1.46 KB
/
timethis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from time import time
from collections import defaultdict
from inspect import isfunction
from atexit import register
total_time = defaultdict(lambda: 0)
timing = {}
def timethis(f):
def wrap(*args, **kwargs):
start = time()
ret = f(*args)
end = time()
total_time[f.__name__ + "()"] += (end - start)
return ret
return wrap
def timefrom(id):
if id in timing:
raise SyntaxError("Missing timeto function for id: " + id)
else:
start = time()
timing[id] = start
def timeto(id):
if id not in timing:
raise SyntaxError("Missing timefrom function for id: " + id)
else:
end = time()
total_time[id] += (end - timing[id])
del timing[id]
def autotime(namespace, module_name='__main__'):
for name, obj in namespace.items():
if isfunction(obj) and obj.__module__ == module_name:
namespace[name] = timethis(namespace[name])
def report():
if timing:
ids = list(timing.keys()).__str__()
raise SyntaxError("Missing timeto function for id: " + ids)
header = "-----------------------------------\n"\
+ "| Report |\n"\
+ "-----------------------------------"
rule = "-----------------------------------"
print(header)
for func in total_time.items():
print("|{:20}|\t{:10.6f}|".format(func[0], func[1]))
print(rule)
register(report)