-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_stat.py
86 lines (75 loc) · 2.34 KB
/
time_stat.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import time
from threading import Lock, current_thread
class TimeStat:
_start_time = {}
_cnt = {}
_sum_time = {}
_lock = Lock()
@classmethod
def start(cls, name):
with cls._lock:
thread_id = current_thread().ident
cls._start_time[(thread_id, name)] = time.time()
@classmethod
def end(cls, name):
with cls._lock:
thread_id = current_thread().ident
if (thread_id, name) in cls._start_time:
inc_time = time.time() - cls._start_time[(thread_id, name)]
cls._add_time(name, inc_time)
del cls._start_time[(thread_id, name)]
else:
raise RuntimeError("end but no start")
@classmethod
def _add_time(cls, name, inc_time):
if name not in cls._sum_time:
cls._sum_time[name] = 0
cls._cnt[name] = 0
cls._sum_time[name] += inc_time
cls._cnt[name] += 1
@classmethod
def add_time(cls, name, inc_time):
with cls._lock:
cls._add_time(name, inc_time)
@classmethod
def report(cls):
data = {
'name': [],
'count': [],
'total_time': [],
'average_time': []
}
for name in cls._sum_time:
data['name'].append(name)
data['count'].append(cls._cnt[name])
data['total_time'].append(cls._sum_time[name])
data['average_time'].append(cls._sum_time[name] / cls._cnt[name])
return data
@classmethod
def get_average_data(cls):
name_2_values = {}
for name in cls._sum_time.keys():
total = cls._sum_time[name]
count = cls._cnt[name]
aver = total / count
name_2_values[name] = aver
return name_2_values
@classmethod
def get_sum_data(cls):
name_2_values = {}
for name in cls._sum_time.keys():
total = cls._sum_time[name]
name_2_values[name] = total
return name_2_values
@classmethod
def get_cnt_data(cls):
name_2_values = {}
for name in cls._sum_time.keys():
name_2_values[name] = cls._cnt[name]
return name_2_values
@classmethod
def clear(cls):
cls._start_time = {}
cls._cnt = {}
cls._sum_time = {}
cls._lock = Lock()