-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer_stack.py
More file actions
204 lines (159 loc) · 6.23 KB
/
Copy pathtimer_stack.py
File metadata and controls
204 lines (159 loc) · 6.23 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import time
from typing import Dict, List, Optional, Tuple
from collections import defaultdict
class Timer:
"""A simple timer that can be started and stopped to measure elapsed time."""
def __init__(self, name: str) -> None:
self.name = name
self._start_time: Optional[float] = None
self._elapsed: float = 0.0
self._running: bool = False
def start(self) -> None:
"""Start the timer."""
if self._running:
raise RuntimeError(f"Timer '{self.name}' is already running")
self._start_time = time.perf_counter()
self._running = True
def stop(self) -> None:
"""Stop the timer and accumulate elapsed time."""
if not self._running:
raise RuntimeError(f"Timer '{self.name}' is not running")
if self._start_time is None:
raise RuntimeError(f"Timer '{self.name}' has no start time")
self._elapsed += time.perf_counter() - self._start_time
self._start_time = None
self._running = False
def elapsed(self) -> float:
"""Return the total elapsed time in seconds."""
if self._running and self._start_time is not None:
return self._elapsed + (time.perf_counter() - self._start_time)
return self._elapsed
def reset(self) -> None:
"""Reset the timer to zero."""
self._elapsed = 0.0
self._start_time = None
self._running = False
@property
def running(self) -> bool:
"""Return whether the timer is currently running."""
return self._running
class TimerStack:
"""A stack-based hierarchical timer manager."""
def __init__(self) -> None:
self._timers: Dict[str, Timer] = {}
self._stack: List[str] = []
self._call_counts: Dict[str, int] = defaultdict(int)
def start(self, name: str) -> None:
"""Start a timer with the given name."""
if name not in self._timers:
self._timers[name] = Timer(name)
self._timers[name].start()
self._stack.append(name)
self._call_counts[name] += 1
def stop(self) -> str:
"""Stop the most recently started timer."""
if not self._stack:
raise RuntimeError("No active timers to stop")
name = self._stack.pop()
self._timers[name].stop()
return name
def __enter__(self) -> 'TimerStack':
"""Enter context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""Exit context manager, stopping all remaining timers."""
while self._stack:
self.stop()
def get_timer(self, name: str) -> Optional[Timer]:
"""Get a timer by name."""
return self._timers.get(name)
def get_elapsed(self, name: str) -> float:
"""Get elapsed time for a timer by name."""
timer = self._timers.get(name)
return timer.elapsed() if timer else 0.0
def get_call_count(self, name: str) -> int:
"""Get the number of times a timer was started."""
return self._call_counts.get(name, 0)
def get_all_timers(self) -> Dict[str, Timer]:
"""Get all timers."""
return self._timers.copy()
def report(self) -> 'Report':
"""Generate a report of all timer data."""
return Report(
timers=self._timers.copy(),
call_counts=dict(self._call_counts),
stack_depth=len(self._stack)
)
class Report:
"""A report containing timer statistics."""
def __init__(self, timers: Dict[str, Timer], call_counts: Dict[str, int], stack_depth: int) -> None:
self.timers = timers
self.call_counts = call_counts
self.stack_depth = stack_depth
self.timestamp = time.time()
def format_report(self) -> str:
"""Format the report as a string."""
if not self.timers:
return "No timers recorded."
lines = ["Timer Report:"]
lines.append("-" * 50)
lines.append(f"{'Name':<20} {'Time (s)':<12} {'Calls':<8} {'Avg Time (s)':<12}")
lines.append("-" * 50)
# Sort timers by elapsed time (descending)
sorted_timers = sorted(self.timers.items(), key=lambda x: x[1].elapsed(), reverse=True)
for name, timer in sorted_timers:
elapsed = timer.elapsed()
calls = self.call_counts.get(name, 0)
avg_time = elapsed / calls if calls > 0 else 0
lines.append(f"{name:<20} {elapsed:<12.6f} {calls:<8} {avg_time:<12.6f}")
lines.append("-" * 50)
lines.append(f"Active timers: {self.stack_depth}")
lines.append(f"Report generated: {time.ctime(self.timestamp)}")
return "\n".join(lines)
def __str__(self) -> str:
return self.format_report()
def demo() -> None:
"""Demonstrate the timer functionality."""
print("Starting timer demo...")
# Basic timer usage
timer = Timer("test")
timer.start()
time.sleep(0.01) # 10ms
timer.stop()
print(f"Basic timer result: {timer.elapsed():.6f} seconds")
# Timer stack usage
with TimerStack() as stack:
stack.start("main")
# Simulate some work
stack.start("setup")
time.sleep(0.005) # 5ms
stack.stop()
# Nested timers
stack.start("processing")
stack.start("phase1")
time.sleep(0.01) # 10ms
stack.stop()
stack.start("phase2")
time.sleep(0.015) # 15ms
stack.stop()
stack.stop() # processing
stack.start("teardown")
time.sleep(0.002) # 2ms
stack.stop()
stack.stop() # main
# Generate and print report
report = stack.report()
print("\n" + str(report))
# Demonstrate multiple calls to same timer
with TimerStack() as stack:
for i in range(3):
stack.start("loop_task")
time.sleep(0.001 * (i + 1)) # 1ms, 2ms, 3ms
stack.stop()
stack.start("final_task")
time.sleep(0.005) # 5ms
stack.stop()
report = stack.report()
print("\n" + str(report))
if __name__ == "__main__":
demo()