Skip to content

Commit ff7f62e

Browse files
authored
gh-142927: Tachyon: Comma separate thousands and fix singular/plurals (#142934)
1 parent 3960878 commit ff7f62e

File tree

5 files changed

+64
-46
lines changed

5 files changed

+64
-46
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import locale
2+
3+
4+
def fmt(value: int | float, decimals: int = 1) -> str:
5+
return locale.format_string(f'%.{decimals}f', value, grouping=True)

Lib/profiling/sampling/_heatmap_assets/heatmap.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,10 +577,12 @@ function populateBytecodePanel(panel, button) {
577577
else if (specPct >= 33) specClass = 'medium';
578578

579579
// Build specialization summary
580+
const instruction_word = instructions.length === 1 ? 'instruction' : 'instructions';
581+
const sample_word = totalSamples === 1 ? 'sample' : 'samples';
580582
let html = `<div class="bytecode-spec-summary ${specClass}">
581583
<span class="spec-pct">${specPct}%</span>
582584
<span class="spec-label">specialized</span>
583-
<span class="spec-detail">(${specializedCount}/${instructions.length} instructions, ${specializedSamples.toLocaleString()}/${totalSamples.toLocaleString()} samples)</span>
585+
<span class="spec-detail">(${specializedCount}/${instructions.length} ${instruction_word}, ${specializedSamples.toLocaleString()}/${totalSamples.toLocaleString()} ${sample_word})</span>
584586
</div>`;
585587

586588
html += '<div class="bytecode-header">' +

Lib/profiling/sampling/cli.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import argparse
44
import importlib.util
5+
import locale
56
import os
67
import selectors
78
import socket
@@ -634,6 +635,16 @@ def _validate_args(args, parser):
634635

635636
def main():
636637
"""Main entry point for the CLI."""
638+
# Set locale for number formatting, restore on exit
639+
old_locale = locale.setlocale(locale.LC_ALL, None)
640+
locale.setlocale(locale.LC_ALL, "")
641+
try:
642+
_main()
643+
finally:
644+
locale.setlocale(locale.LC_ALL, old_locale)
645+
646+
647+
def _main():
637648
# Create the main parser
638649
parser = argparse.ArgumentParser(
639650
description=_HELP_DESCRIPTION,

Lib/profiling/sampling/heatmap_collector.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import html
66
import importlib.resources
77
import json
8+
import locale
89
import math
910
import os
1011
import platform
@@ -15,6 +16,7 @@
1516
from typing import Dict, List, Tuple
1617

1718
from ._css_utils import get_combined_css
19+
from ._format_utils import fmt
1820
from .collector import normalize_location, extract_lineno
1921
from .stack_collector import StackTraceCollector
2022

@@ -343,7 +345,7 @@ def render_hierarchical_html(self, trees: Dict[str, TreeNode]) -> str:
343345
<div class="type-header" onclick="toggleTypeSection(this)">
344346
<span class="type-icon">{icon}</span>
345347
<span class="type-title">{type_names[module_type]}</span>
346-
<span class="type-stats">({tree.count} {file_word}, {tree.samples:,} {sample_word})</span>
348+
<span class="type-stats">({tree.count} {file_word}, {tree.samples:n} {sample_word})</span>
347349
</div>
348350
<div class="type-content"{content_style}>
349351
'''
@@ -390,7 +392,7 @@ def _render_folder(self, node: TreeNode, name: str, level: int = 1) -> str:
390392
parts.append(f'{indent} <span class="folder-icon">▶</span>')
391393
parts.append(f'{indent} <span class="folder-name">📁 {html.escape(name)}</span>')
392394
parts.append(f'{indent} <span class="folder-stats">'
393-
f'({node.count} {file_word}, {node.samples:,} {sample_word})</span>')
395+
f'({node.count} {file_word}, {node.samples:n} {sample_word})</span>')
394396
parts.append(f'{indent} </div>')
395397
parts.append(f'{indent} <div class="folder-content" style="display: none;">')
396398

@@ -431,10 +433,11 @@ def _render_file_item(self, stat: FileStats, indent: str = '') -> str:
431433
bar_width = min(stat.percentage, 100)
432434

433435
html_file = self.file_index[stat.filename]
436+
s = "" if stat.total_samples == 1 else "s"
434437

435438
return (f'{indent}<div class="file-item">\n'
436439
f'{indent} <a href="{html_file}" class="file-link" title="{full_path}">📄 {module_name}</a>\n'
437-
f'{indent} <span class="file-samples">{stat.total_samples:,} samples</span>\n'
440+
f'{indent} <span class="file-samples">{stat.total_samples:n} sample{s}</span>\n'
438441
f'{indent} <div class="heatmap-bar-container"><div class="heatmap-bar" style="width: {bar_width}px; height: {self.heatmap_bar_height}px;" data-intensity="{intensity:.3f}"></div></div>\n'
439442
f'{indent}</div>\n')
440443

@@ -761,7 +764,8 @@ def _print_export_summary(self, output_dir, file_stats: List[FileStats]):
761764
"""Print summary of exported heatmap."""
762765
print(f"Heatmap output written to {output_dir}/")
763766
print(f" - Index: {output_dir / 'index.html'}")
764-
print(f" - {len(file_stats)} source file(s) analyzed")
767+
s = "" if len(file_stats) == 1 else "s"
768+
print(f" - {len(file_stats)} source file{s} analyzed")
765769

766770
def _calculate_file_stats(self) -> List[FileStats]:
767771
"""Calculate statistics for each file.
@@ -824,7 +828,7 @@ def _generate_index_html(self, index_path: Path, file_stats: List[FileStats]):
824828
# Format error rate and missed samples with bar classes
825829
error_rate = self.stats.get('error_rate')
826830
if error_rate is not None:
827-
error_rate_str = f"{error_rate:.1f}%"
831+
error_rate_str = f"{fmt(error_rate)}%"
828832
error_rate_width = min(error_rate, 100)
829833
# Determine bar color class based on rate
830834
if error_rate < 5:
@@ -840,7 +844,7 @@ def _generate_index_html(self, index_path: Path, file_stats: List[FileStats]):
840844

841845
missed_samples = self.stats.get('missed_samples')
842846
if missed_samples is not None:
843-
missed_samples_str = f"{missed_samples:.1f}%"
847+
missed_samples_str = f"{fmt(missed_samples)}%"
844848
missed_samples_width = min(missed_samples, 100)
845849
if missed_samples < 5:
846850
missed_samples_class = "good"
@@ -859,10 +863,10 @@ def _generate_index_html(self, index_path: Path, file_stats: List[FileStats]):
859863
"<!-- INLINE_JS -->": f"<script>\n{self._template_loader.index_js}\n</script>",
860864
"<!-- PYTHON_LOGO -->": self._template_loader.logo_html,
861865
"<!-- PYTHON_VERSION -->": f"{sys.version_info.major}.{sys.version_info.minor}",
862-
"<!-- NUM_FILES -->": str(len(file_stats)),
863-
"<!-- TOTAL_SAMPLES -->": f"{self._total_samples:,}",
864-
"<!-- DURATION -->": f"{self.stats.get('duration_sec', 0):.1f}s",
865-
"<!-- SAMPLE_RATE -->": f"{self.stats.get('sample_rate', 0):.1f}",
866+
"<!-- NUM_FILES -->": f"{len(file_stats):n}",
867+
"<!-- TOTAL_SAMPLES -->": f"{self._total_samples:n}",
868+
"<!-- DURATION -->": fmt(self.stats.get('duration_sec', 0)),
869+
"<!-- SAMPLE_RATE -->": fmt(self.stats.get('sample_rate', 0)),
866870
"<!-- ERROR_RATE -->": error_rate_str,
867871
"<!-- ERROR_RATE_WIDTH -->": str(error_rate_width),
868872
"<!-- ERROR_RATE_CLASS -->": error_rate_class,
@@ -906,12 +910,12 @@ def _generate_file_html(self, output_path: Path, filename: str,
906910
# Populate template
907911
replacements = {
908912
"<!-- FILENAME -->": html.escape(filename),
909-
"<!-- TOTAL_SAMPLES -->": f"{file_stat.total_samples:,}",
910-
"<!-- TOTAL_SELF_SAMPLES -->": f"{file_stat.total_self_samples:,}",
911-
"<!-- NUM_LINES -->": str(file_stat.num_lines),
912-
"<!-- PERCENTAGE -->": f"{file_stat.percentage:.2f}",
913-
"<!-- MAX_SAMPLES -->": str(file_stat.max_samples),
914-
"<!-- MAX_SELF_SAMPLES -->": str(file_stat.max_self_samples),
913+
"<!-- TOTAL_SAMPLES -->": f"{file_stat.total_samples:n}",
914+
"<!-- TOTAL_SELF_SAMPLES -->": f"{file_stat.total_self_samples:n}",
915+
"<!-- NUM_LINES -->": f"{file_stat.num_lines:n}",
916+
"<!-- PERCENTAGE -->": fmt(file_stat.percentage, 2),
917+
"<!-- MAX_SAMPLES -->": f"{file_stat.max_samples:n}",
918+
"<!-- MAX_SELF_SAMPLES -->": f"{file_stat.max_self_samples:n}",
915919
"<!-- CODE_LINES -->": ''.join(code_lines_html),
916920
"<!-- INLINE_CSS -->": f"<style>\n{self._template_loader.file_css}\n</style>",
917921
"<!-- INLINE_JS -->": f"<script>\n{self._template_loader.file_js}\n</script>",
@@ -948,9 +952,9 @@ def _build_line_html(self, line_num: int, line_content: str,
948952
else:
949953
self_intensity = 0
950954

951-
self_display = f"{self_samples:,}" if self_samples > 0 else ""
952-
cumulative_display = f"{cumulative_samples:,}"
953-
tooltip = f"Self: {self_samples:,}, Total: {cumulative_samples:,}"
955+
self_display = f"{self_samples:n}" if self_samples > 0 else ""
956+
cumulative_display = f"{cumulative_samples:n}"
957+
tooltip = f"Self: {self_samples:n}, Total: {cumulative_samples:n}"
954958
else:
955959
cumulative_intensity = 0
956960
self_intensity = 0
@@ -1205,7 +1209,7 @@ def _create_navigation_button(self, items_with_counts: List[Tuple[str, int, str,
12051209
file, line, func, count = valid_items[0]
12061210
target_html = self.file_index[file]
12071211
nav_data = json.dumps({'link': f"{target_html}#line-{line}", 'func': func})
1208-
title = f"Go to {btn_class}: {html.escape(func)} ({count:,} samples)"
1212+
title = f"Go to {btn_class}: {html.escape(func)} ({count:n} samples)"
12091213
return f'<button class="nav-btn {btn_class}" data-nav=\'{html.escape(nav_data)}\' title="{title}">{arrow}</button>'
12101214

12111215
# Multiple items - create menu
@@ -1220,5 +1224,5 @@ def _create_navigation_button(self, items_with_counts: List[Tuple[str, int, str,
12201224
for file, line, func, count in valid_items
12211225
]
12221226
items_json = html.escape(json.dumps(items_data))
1223-
title = f"{len(items_data)} {btn_class}s ({total_samples:,} samples)"
1227+
title = f"{len(items_data)} {btn_class}s ({total_samples:n} samples)"
12241228
return f'<button class="nav-btn {btn_class}" data-nav-multi=\'{items_json}\' title="{title}">{arrow}</button>'

Lib/profiling/sampling/sample.py

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
import _remote_debugging
22
import os
3-
import pstats
43
import statistics
54
import sys
65
import sysconfig
76
import time
87
from collections import deque
98
from _colorize import ANSIColors
109

11-
from .pstats_collector import PstatsCollector
12-
from .stack_collector import CollapsedStackCollector, FlamegraphCollector
13-
from .heatmap_collector import HeatmapCollector
14-
from .gecko_collector import GeckoCollector
1510
from .constants import (
1611
PROFILING_MODE_WALL,
1712
PROFILING_MODE_CPU,
1813
PROFILING_MODE_GIL,
1914
PROFILING_MODE_ALL,
2015
PROFILING_MODE_EXCEPTION,
2116
)
17+
from ._format_utils import fmt
2218
try:
2319
from .live_collector import LiveStatsCollector
2420
except ImportError:
@@ -135,9 +131,9 @@ def sample(self, collector, duration_sec=10, *, async_aware=False):
135131
# Don't print stats for live mode (curses is handling display)
136132
is_live_mode = LiveStatsCollector is not None and isinstance(collector, LiveStatsCollector)
137133
if not is_live_mode:
138-
print(f"Captured {num_samples} samples in {running_time:.2f} seconds")
139-
print(f"Sample rate: {sample_rate:.2f} samples/sec")
140-
print(f"Error rate: {error_rate:.2f}%")
134+
print(f"Captured {num_samples:n} samples in {fmt(running_time, 2)} seconds")
135+
print(f"Sample rate: {fmt(sample_rate, 2)} samples/sec")
136+
print(f"Error rate: {fmt(error_rate, 2)}")
141137

142138
# Print unwinder stats if stats collection is enabled
143139
if self.collect_stats:
@@ -151,7 +147,7 @@ def sample(self, collector, duration_sec=10, *, async_aware=False):
151147
print(
152148
f"Warning: missed {expected_samples - num_samples} samples "
153149
f"from the expected total of {expected_samples} "
154-
f"({(expected_samples - num_samples) / expected_samples * 100:.2f}%)"
150+
f"({fmt((expected_samples - num_samples) / expected_samples * 100, 2)}%)"
155151
)
156152

157153
def _print_realtime_stats(self):
@@ -185,16 +181,16 @@ def _print_realtime_stats(self):
185181
total = hits + partial + misses
186182
if total > 0:
187183
hit_pct = (hits + partial) / total * 100
188-
cache_stats_str = f" {ANSIColors.MAGENTA}Cache: {hit_pct:.1f}% ({hits}+{partial}/{misses}){ANSIColors.RESET}"
184+
cache_stats_str = f" {ANSIColors.MAGENTA}Cache: {fmt(hit_pct)}% ({hits}+{partial}/{misses}){ANSIColors.RESET}"
189185
except RuntimeError:
190186
pass
191187

192188
# Clear line and print stats
193189
print(
194190
f"\r\033[K{ANSIColors.BOLD_BLUE}Stats:{ANSIColors.RESET} "
195-
f"{ANSIColors.YELLOW}{mean_hz:.1f}Hz ({mean_us_per_sample:.1f}µs){ANSIColors.RESET} "
196-
f"{ANSIColors.GREEN}Min: {min_hz:.1f}Hz{ANSIColors.RESET} "
197-
f"{ANSIColors.RED}Max: {max_hz:.1f}Hz{ANSIColors.RESET} "
191+
f"{ANSIColors.YELLOW}{fmt(mean_hz)}Hz ({fmt(mean_us_per_sample)}µs){ANSIColors.RESET} "
192+
f"{ANSIColors.GREEN}Min: {fmt(min_hz)}Hz{ANSIColors.RESET} "
193+
f"{ANSIColors.RED}Max: {fmt(max_hz)}Hz{ANSIColors.RESET} "
198194
f"{ANSIColors.CYAN}N={self.total_samples}{ANSIColors.RESET}"
199195
f"{cache_stats_str}",
200196
end="",
@@ -224,10 +220,10 @@ def _print_unwinder_stats(self):
224220
misses_pct = (frame_cache_misses / total_lookups * 100) if total_lookups > 0 else 0
225221

226222
print(f" {ANSIColors.CYAN}Frame Cache:{ANSIColors.RESET}")
227-
print(f" Total samples: {total_samples:,}")
228-
print(f" Full hits: {frame_cache_hits:,} ({ANSIColors.GREEN}{hits_pct:.1f}%{ANSIColors.RESET})")
229-
print(f" Partial hits: {frame_cache_partial_hits:,} ({ANSIColors.YELLOW}{partial_pct:.1f}%{ANSIColors.RESET})")
230-
print(f" Misses: {frame_cache_misses:,} ({ANSIColors.RED}{misses_pct:.1f}%{ANSIColors.RESET})")
223+
print(f" Total samples: {total_samples:n}")
224+
print(f" Full hits: {frame_cache_hits:n} ({ANSIColors.GREEN}{fmt(hits_pct)}%{ANSIColors.RESET})")
225+
print(f" Partial hits: {frame_cache_partial_hits:n} ({ANSIColors.YELLOW}{fmt(partial_pct)}%{ANSIColors.RESET})")
226+
print(f" Misses: {frame_cache_misses:n} ({ANSIColors.RED}{fmt(misses_pct)}%{ANSIColors.RESET})")
231227

232228
# Frame read stats
233229
frames_from_cache = stats.get('frames_read_from_cache', 0)
@@ -237,8 +233,8 @@ def _print_unwinder_stats(self):
237233
memory_frame_pct = (frames_from_memory / total_frames * 100) if total_frames > 0 else 0
238234

239235
print(f" {ANSIColors.CYAN}Frame Reads:{ANSIColors.RESET}")
240-
print(f" From cache: {frames_from_cache:,} ({ANSIColors.GREEN}{cache_frame_pct:.1f}%{ANSIColors.RESET})")
241-
print(f" From memory: {frames_from_memory:,} ({ANSIColors.RED}{memory_frame_pct:.1f}%{ANSIColors.RESET})")
236+
print(f" From cache: {frames_from_cache:n} ({ANSIColors.GREEN}{fmt(cache_frame_pct)}%{ANSIColors.RESET})")
237+
print(f" From memory: {frames_from_memory:n} ({ANSIColors.RED}{fmt(memory_frame_pct)}%{ANSIColors.RESET})")
242238

243239
# Code object cache stats
244240
code_hits = stats.get('code_object_cache_hits', 0)
@@ -248,20 +244,20 @@ def _print_unwinder_stats(self):
248244
code_misses_pct = (code_misses / total_code * 100) if total_code > 0 else 0
249245

250246
print(f" {ANSIColors.CYAN}Code Object Cache:{ANSIColors.RESET}")
251-
print(f" Hits: {code_hits:,} ({ANSIColors.GREEN}{code_hits_pct:.1f}%{ANSIColors.RESET})")
252-
print(f" Misses: {code_misses:,} ({ANSIColors.RED}{code_misses_pct:.1f}%{ANSIColors.RESET})")
247+
print(f" Hits: {code_hits:n} ({ANSIColors.GREEN}{fmt(code_hits_pct)}%{ANSIColors.RESET})")
248+
print(f" Misses: {code_misses:n} ({ANSIColors.RED}{fmt(code_misses_pct)}%{ANSIColors.RESET})")
253249

254250
# Memory operations
255251
memory_reads = stats.get('memory_reads', 0)
256252
memory_bytes = stats.get('memory_bytes_read', 0)
257253
if memory_bytes >= 1024 * 1024:
258-
memory_str = f"{memory_bytes / (1024 * 1024):.1f} MB"
254+
memory_str = f"{fmt(memory_bytes / (1024 * 1024))} MB"
259255
elif memory_bytes >= 1024:
260-
memory_str = f"{memory_bytes / 1024:.1f} KB"
256+
memory_str = f"{fmt(memory_bytes / 1024)} KB"
261257
else:
262258
memory_str = f"{memory_bytes} B"
263259
print(f" {ANSIColors.CYAN}Memory:{ANSIColors.RESET}")
264-
print(f" Read operations: {memory_reads:,} ({memory_str})")
260+
print(f" Read operations: {memory_reads:n} ({memory_str})")
265261

266262
# Stale invalidations
267263
stale_invalidations = stats.get('stale_cache_invalidations', 0)

0 commit comments

Comments
 (0)