|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import datetime as dt |
2 | 4 | import re |
3 | 5 |
|
@@ -58,42 +60,27 @@ def format_time(nanoseconds: int) -> str: |
58 | 60 | raise TypeError("Input must be an integer.") |
59 | 61 | if nanoseconds < 0: |
60 | 62 | raise ValueError("Input must be a positive integer.") |
61 | | - conversions = [(1_000_000_000, "s"), (1_000_000, "ms"), (1_000, "μs"), (1, "ns")] |
62 | 63 |
|
63 | | - # Handle nanoseconds case directly (no decimal formatting needed) |
64 | 64 | if nanoseconds < 1_000: |
65 | 65 | return f"{nanoseconds}ns" |
66 | | - |
67 | | - # Find appropriate unit |
68 | | - for divisor, unit in conversions: |
69 | | - if nanoseconds >= divisor: |
70 | | - value = nanoseconds / divisor |
71 | | - int_value = nanoseconds // divisor |
72 | | - |
73 | | - # Use integer formatting for values >= 100 |
74 | | - if int_value >= 100: |
75 | | - formatted_value = f"{int_value:.0f}" |
76 | | - # Format with precision for 3 significant digits |
77 | | - elif value >= 100: |
78 | | - formatted_value = f"{value:.0f}" |
79 | | - elif value >= 10: |
80 | | - formatted_value = f"{value:.1f}" |
81 | | - else: |
82 | | - formatted_value = f"{value:.2f}" |
83 | | - |
84 | | - return f"{formatted_value}{unit}" |
85 | | - |
86 | | - # This should never be reached, but included for completeness |
87 | | - return f"{nanoseconds}ns" |
| 66 | + if nanoseconds < 1_000_000: |
| 67 | + value = nanoseconds / 1_000 |
| 68 | + return f"{value:.2f}μs" if value < 10 else (f"{value:.1f}μs" if value < 100 else f"{int(value)}μs") |
| 69 | + if nanoseconds < 1_000_000_000: |
| 70 | + value = nanoseconds / 1_000_000 |
| 71 | + return f"{value:.2f}ms" if value < 10 else (f"{value:.1f}ms" if value < 100 else f"{int(value)}ms") |
| 72 | + value = nanoseconds / 1_000_000_000 |
| 73 | + return f"{value:.2f}s" if value < 10 else (f"{value:.1f}s" if value < 100 else f"{int(value)}s") |
88 | 74 |
|
89 | 75 |
|
90 | 76 | def format_perf(percentage: float) -> str: |
91 | 77 | """Format percentage into a human-readable string with 3 significant digits when needed.""" |
92 | | - percentage_abs = abs(percentage) |
93 | | - if percentage_abs >= 100: |
| 78 | + # Branch order optimized |
| 79 | + abs_perc = abs(percentage) |
| 80 | + if abs_perc >= 100: |
94 | 81 | return f"{percentage:.0f}" |
95 | | - if percentage_abs >= 10: |
| 82 | + if abs_perc >= 10: |
96 | 83 | return f"{percentage:.1f}" |
97 | | - if percentage_abs >= 1: |
| 84 | + if abs_perc >= 1: |
98 | 85 | return f"{percentage:.2f}" |
99 | 86 | return f"{percentage:.3f}" |
0 commit comments