Skip to content

Commit a13a4aa

Browse files
committed
Standardise time units
1 parent fc2f0fe commit a13a4aa

File tree

10 files changed

+46
-41
lines changed

10 files changed

+46
-41
lines changed

Lib/profiling/sampling/_child_monitor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
_CHILD_POLL_INTERVAL_SEC = 0.1
1717

1818
# Default timeout for waiting on child profilers
19-
_DEFAULT_WAIT_TIMEOUT = 30.0
19+
_DEFAULT_WAIT_TIMEOUT_SEC = 30.0
2020

2121
# Maximum number of child profilers to spawn (prevents resource exhaustion)
2222
_MAX_CHILD_PROFILERS = 100
@@ -138,7 +138,7 @@ def spawned_profilers(self):
138138
with self._lock:
139139
return list(self._spawned_profilers)
140140

141-
def wait_for_profilers(self, timeout=_DEFAULT_WAIT_TIMEOUT):
141+
def wait_for_profilers(self, timeout=_DEFAULT_WAIT_TIMEOUT_SEC):
142142
"""
143143
Wait for all spawned child profilers to complete.
144144

Lib/profiling/sampling/_sync_coordinator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ def _validate_arguments(args: List[str]) -> tuple[int, str, List[str]]:
7373

7474
# Constants for socket communication
7575
_MAX_RETRIES = 3
76-
_INITIAL_RETRY_DELAY = 0.1
77-
_SOCKET_TIMEOUT = 2.0
76+
_INITIAL_RETRY_DELAY_SEC = 0.1
77+
_SOCKET_TIMEOUT_SEC = 2.0
7878
_READY_MESSAGE = b"ready"
7979

8080

@@ -93,14 +93,14 @@ def _signal_readiness(sync_port: int) -> None:
9393
for attempt in range(_MAX_RETRIES):
9494
try:
9595
# Use context manager for automatic cleanup
96-
with socket.create_connection(("127.0.0.1", sync_port), timeout=_SOCKET_TIMEOUT) as sock:
96+
with socket.create_connection(("127.0.0.1", sync_port), timeout=_SOCKET_TIMEOUT_SEC) as sock:
9797
sock.send(_READY_MESSAGE)
9898
return
9999
except (socket.error, OSError) as e:
100100
last_error = e
101101
if attempt < _MAX_RETRIES - 1:
102102
# Exponential backoff before retry
103-
time.sleep(_INITIAL_RETRY_DELAY * (2 ** attempt))
103+
time.sleep(_INITIAL_RETRY_DELAY_SEC * (2 ** attempt))
104104

105105
# If we get here, all retries failed
106106
raise SyncError(f"Failed to signal readiness after {_MAX_RETRIES} attempts: {last_error}") from last_error

Lib/profiling/sampling/cli.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ class CustomFormatter(
6666

6767

6868
# Constants for socket synchronization
69-
_SYNC_TIMEOUT = 5.0
70-
_PROCESS_KILL_TIMEOUT = 2.0
69+
_SYNC_TIMEOUT_SEC = 5.0
70+
_PROCESS_KILL_TIMEOUT_SEC = 2.0
7171
_READY_MESSAGE = b"ready"
7272
_RECV_BUFFER_SIZE = 1024
7373

@@ -239,7 +239,7 @@ def _run_with_sync(original_cmd, suppress_output=False):
239239
sync_sock.bind(("127.0.0.1", 0)) # Let OS choose a free port
240240
sync_port = sync_sock.getsockname()[1]
241241
sync_sock.listen(1)
242-
sync_sock.settimeout(_SYNC_TIMEOUT)
242+
sync_sock.settimeout(_SYNC_TIMEOUT_SEC)
243243

244244
# Get current working directory to preserve it
245245
cwd = os.getcwd()
@@ -268,7 +268,7 @@ def _run_with_sync(original_cmd, suppress_output=False):
268268
process = subprocess.Popen(cmd, **popen_kwargs)
269269

270270
try:
271-
_wait_for_ready_signal(sync_sock, process, _SYNC_TIMEOUT)
271+
_wait_for_ready_signal(sync_sock, process, _SYNC_TIMEOUT_SEC)
272272

273273
# Close stderr pipe if we were capturing it
274274
if process.stderr:
@@ -279,7 +279,7 @@ def _run_with_sync(original_cmd, suppress_output=False):
279279
if process.poll() is None:
280280
process.terminate()
281281
try:
282-
process.wait(timeout=_PROCESS_KILL_TIMEOUT)
282+
process.wait(timeout=_PROCESS_KILL_TIMEOUT_SEC)
283283
except subprocess.TimeoutExpired:
284284
process.kill()
285285
process.wait()
@@ -965,7 +965,7 @@ def _handle_run(args):
965965
if process.poll() is None:
966966
process.terminate()
967967
try:
968-
process.wait(timeout=_PROCESS_KILL_TIMEOUT)
968+
process.wait(timeout=_PROCESS_KILL_TIMEOUT_SEC)
969969
except subprocess.TimeoutExpired:
970970
process.kill()
971971
process.wait()

Lib/profiling/sampling/constants.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
"""Constants for the sampling profiler."""
22

3+
# Time unit conversion constants
4+
MICROSECONDS_PER_SECOND = 1_000_000
5+
MILLISECONDS_PER_SECOND = 1_000
6+
37
# Profiling mode constants
48
PROFILING_MODE_WALL = 0
59
PROFILING_MODE_CPU = 1

Lib/profiling/sampling/live_collector/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@
114114
from .constants import (
115115
MICROSECONDS_PER_SECOND,
116116
DISPLAY_UPDATE_HZ,
117-
DISPLAY_UPDATE_INTERVAL,
117+
DISPLAY_UPDATE_INTERVAL_SEC,
118118
MIN_TERMINAL_WIDTH,
119119
MIN_TERMINAL_HEIGHT,
120120
WIDTH_THRESHOLD_SAMPLE_PCT,
@@ -165,7 +165,7 @@
165165
# Constants
166166
"MICROSECONDS_PER_SECOND",
167167
"DISPLAY_UPDATE_HZ",
168-
"DISPLAY_UPDATE_INTERVAL",
168+
"DISPLAY_UPDATE_INTERVAL_SEC",
169169
"MIN_TERMINAL_WIDTH",
170170
"MIN_TERMINAL_HEIGHT",
171171
"WIDTH_THRESHOLD_SAMPLE_PCT",

Lib/profiling/sampling/live_collector/collector.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
)
2525
from .constants import (
2626
MICROSECONDS_PER_SECOND,
27-
DISPLAY_UPDATE_INTERVAL,
27+
DISPLAY_UPDATE_INTERVAL_SEC,
2828
MIN_TERMINAL_WIDTH,
2929
MIN_TERMINAL_HEIGHT,
3030
HEADER_LINES,
@@ -157,7 +157,7 @@ def __init__(
157157
self.max_sample_rate = 0 # Track maximum sample rate seen
158158
self.successful_samples = 0 # Track samples that captured frames
159159
self.failed_samples = 0 # Track samples that failed to capture frames
160-
self.display_update_interval = DISPLAY_UPDATE_INTERVAL # Instance variable for display refresh rate
160+
self.display_update_interval_sec = DISPLAY_UPDATE_INTERVAL_SEC # Instance variable for display refresh rate
161161

162162
# Thread status statistics (bit flags)
163163
self.thread_status_counts = {
@@ -410,7 +410,7 @@ def collect(self, stack_frames, timestamp_us=None):
410410
if (
411411
self._last_display_update is None
412412
or (current_time - self._last_display_update)
413-
>= self.display_update_interval
413+
>= self.display_update_interval_sec
414414
):
415415
self._update_display()
416416
self._last_display_update = current_time
@@ -987,14 +987,14 @@ def _handle_input(self):
987987

988988
elif ch == ord("+") or ch == ord("="):
989989
# Decrease update interval (faster refresh)
990-
self.display_update_interval = max(
991-
0.05, self.display_update_interval - 0.05
990+
self.display_update_interval_sec = max(
991+
0.05, self.display_update_interval_sec - 0.05
992992
) # Min 20Hz
993993

994994
elif ch == ord("-") or ch == ord("_"):
995995
# Increase update interval (slower refresh)
996-
self.display_update_interval = min(
997-
1.0, self.display_update_interval + 0.05
996+
self.display_update_interval_sec = min(
997+
1.0, self.display_update_interval_sec + 0.05
998998
) # Max 1Hz
999999

10001000
elif ch == ord("c") or ch == ord("C"):

Lib/profiling/sampling/live_collector/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
# Display update constants
77
DISPLAY_UPDATE_HZ = 10
8-
DISPLAY_UPDATE_INTERVAL = 1.0 / DISPLAY_UPDATE_HZ # 0.1 seconds
8+
DISPLAY_UPDATE_INTERVAL_SEC = 1.0 / DISPLAY_UPDATE_HZ # 0.1 seconds
99

1010
# Terminal size constraints
1111
MIN_TERMINAL_WIDTH = 60

Lib/profiling/sampling/live_collector/widgets.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
WIDTH_THRESHOLD_CUMUL_PCT,
1414
WIDTH_THRESHOLD_CUMTIME,
1515
MICROSECONDS_PER_SECOND,
16-
DISPLAY_UPDATE_INTERVAL,
16+
DISPLAY_UPDATE_INTERVAL_SEC,
1717
MIN_BAR_WIDTH,
1818
MAX_SAMPLE_RATE_BAR_WIDTH,
1919
MAX_EFFICIENCY_BAR_WIDTH,
@@ -181,7 +181,7 @@ def draw_header_info(self, line, width, elapsed):
181181

182182
# Calculate display refresh rate
183183
refresh_hz = (
184-
1.0 / self.collector.display_update_interval if self.collector.display_update_interval > 0 else 0
184+
1.0 / self.collector.display_update_interval_sec if self.collector.display_update_interval_sec > 0 else 0
185185
)
186186

187187
# Get current view mode and thread display
@@ -235,8 +235,8 @@ def draw_header_info(self, line, width, elapsed):
235235

236236
def format_rate_with_units(self, rate_hz):
237237
"""Format a rate in Hz with appropriate units (Hz, KHz, MHz)."""
238-
if rate_hz >= 1_000_000:
239-
return f"{rate_hz / 1_000_000:.1f}MHz"
238+
if rate_hz >= MICROSECONDS_PER_SECOND:
239+
return f"{rate_hz / MICROSECONDS_PER_SECOND:.1f}MHz"
240240
elif rate_hz >= 1_000:
241241
return f"{rate_hz / 1_000:.1f}KHz"
242242
else:

Lib/profiling/sampling/pstats_collector.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from _colorize import ANSIColors
55
from .collector import Collector, extract_lineno
6+
from .constants import MICROSECONDS_PER_SECOND
67

78

89
class PstatsCollector(Collector):
@@ -68,7 +69,7 @@ def _dump_stats(self, file):
6869

6970
# Needed for compatibility with pstats.Stats
7071
def create_stats(self):
71-
sample_interval_sec = self.sample_interval_usec / 1_000_000
72+
sample_interval_sec = self.sample_interval_usec / MICROSECONDS_PER_SECOND
7273
callers = {}
7374
for fname, call_counts in self.result.items():
7475
total = call_counts["direct_calls"] * sample_interval_sec
@@ -263,7 +264,7 @@ def _determine_best_unit(max_value):
263264
elif max_value >= 0.001:
264265
return "ms", 1000.0
265266
else:
266-
return "μs", 1000000.0
267+
return "μs", float(MICROSECONDS_PER_SECOND)
267268

268269
def _print_summary(self, stats_list, total_samples):
269270
"""Print summary of interesting functions."""

Lib/test/test_profiling/test_sampling_profiler/test_live_collector_interaction.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def setUp(self):
3535
)
3636
self.collector.start_time = time.perf_counter()
3737
# Set a consistent display update interval for tests
38-
self.collector.display_update_interval = 0.1
38+
self.collector.display_update_interval_sec = 0.1
3939

4040
def tearDown(self):
4141
"""Clean up after test."""
@@ -110,45 +110,45 @@ def test_reset_stats(self):
110110

111111
def test_increase_refresh_rate(self):
112112
"""Test increasing refresh rate (faster updates)."""
113-
initial_interval = self.collector.display_update_interval
113+
initial_interval = self.collector.display_update_interval_sec
114114

115115
# Simulate '+' key press (faster = smaller interval)
116116
self.display.simulate_input(ord("+"))
117117
self.collector._handle_input()
118118

119-
self.assertLess(self.collector.display_update_interval, initial_interval)
119+
self.assertLess(self.collector.display_update_interval_sec, initial_interval)
120120

121121
def test_decrease_refresh_rate(self):
122122
"""Test decreasing refresh rate (slower updates)."""
123-
initial_interval = self.collector.display_update_interval
123+
initial_interval = self.collector.display_update_interval_sec
124124

125125
# Simulate '-' key press (slower = larger interval)
126126
self.display.simulate_input(ord("-"))
127127
self.collector._handle_input()
128128

129-
self.assertGreater(self.collector.display_update_interval, initial_interval)
129+
self.assertGreater(self.collector.display_update_interval_sec, initial_interval)
130130

131131
def test_refresh_rate_minimum(self):
132132
"""Test that refresh rate has a minimum (max speed)."""
133-
self.collector.display_update_interval = 0.05 # Set to minimum
133+
self.collector.display_update_interval_sec = 0.05 # Set to minimum
134134

135135
# Try to go faster
136136
self.display.simulate_input(ord("+"))
137137
self.collector._handle_input()
138138

139139
# Should stay at minimum
140-
self.assertEqual(self.collector.display_update_interval, 0.05)
140+
self.assertEqual(self.collector.display_update_interval_sec, 0.05)
141141

142142
def test_refresh_rate_maximum(self):
143143
"""Test that refresh rate has a maximum (min speed)."""
144-
self.collector.display_update_interval = 1.0 # Set to maximum
144+
self.collector.display_update_interval_sec = 1.0 # Set to maximum
145145

146146
# Try to go slower
147147
self.display.simulate_input(ord("-"))
148148
self.collector._handle_input()
149149

150150
# Should stay at maximum
151-
self.assertEqual(self.collector.display_update_interval, 1.0)
151+
self.assertEqual(self.collector.display_update_interval_sec, 1.0)
152152

153153
def test_help_toggle(self):
154154
"""Test help screen toggle."""
@@ -289,23 +289,23 @@ def test_filter_clear_uppercase(self):
289289

290290
def test_increase_refresh_rate_with_equals(self):
291291
"""Test increasing refresh rate with '=' key."""
292-
initial_interval = self.collector.display_update_interval
292+
initial_interval = self.collector.display_update_interval_sec
293293

294294
# Simulate '=' key press (alternative to '+')
295295
self.display.simulate_input(ord("="))
296296
self.collector._handle_input()
297297

298-
self.assertLess(self.collector.display_update_interval, initial_interval)
298+
self.assertLess(self.collector.display_update_interval_sec, initial_interval)
299299

300300
def test_decrease_refresh_rate_with_underscore(self):
301301
"""Test decreasing refresh rate with '_' key."""
302-
initial_interval = self.collector.display_update_interval
302+
initial_interval = self.collector.display_update_interval_sec
303303

304304
# Simulate '_' key press (alternative to '-')
305305
self.display.simulate_input(ord("_"))
306306
self.collector._handle_input()
307307

308-
self.assertGreater(self.collector.display_update_interval, initial_interval)
308+
self.assertGreater(self.collector.display_update_interval_sec, initial_interval)
309309

310310
def test_finished_state_displays_banner(self):
311311
"""Test that finished state shows prominent banner."""

0 commit comments

Comments
 (0)