Repository navigation
Expand file tree
/
Copy pathtimer.py
More file actions
60 lines (48 loc) · 1.59 KB
/
Copy pathtimer.py
File metadata and controls
60 lines (48 loc) · 1.59 KB
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
"""
The code has been taken from WhatsHap.
Link to WhatsHap: https://github.com/whatshap/whatshap
"""
import time
from collections import defaultdict
from contextlib import contextmanager
class StageTimer:
"""Measure run times of multiple non-overlapping stages of a program"""
def __init__(self):
self._start = {}
self._elapsed = defaultdict(float)
self._overall_start_time = time.time()
def start(self, stage):
"""Start measuring elapsed time for a stage"""
self._start[stage] = time.perf_counter()
def stop(self, stage):
"""Stop measuring elapsed time for a stage."""
t = time.perf_counter() - self._start[stage]
assert t > 0
self._elapsed[stage] += t
del self._start[stage]
return t
def elapsed(self, stage):
"""
Return total time spent in a stage, which is the sum of the time spans
between calls to start() and stop(). If the timer is currently running,
its current invocation is not counted.
"""
return self._elapsed[stage]
def sum(self):
"""Return sum of all times"""
return sum(self._elapsed.values())
def total(self):
return time.time() - self._overall_start_time
@contextmanager
def __call__(self, stage):
self.start(stage)
yield
self.stop(stage)
def iterate(self, stage, iterator):
"""Measure iterator runtime"""
self.start(stage)
for item in iterator:
self.stop(stage)
yield item
self.start(stage)
self.stop(stage)