Last active
April 14, 2025 04:11
-
-
Save brianonn/4547ddd9770582bea191d8e98d7a29f2 to your computer and use it in GitHub Desktop.
A Python function to format a float seconds value into a string representation for milliseconds, microseconds, nanoseconds, or picoseconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def format_seconds(seconds): | |
""" | |
Format a decimal number of seconds into the most appropriate unit | |
(ms, μs, ns, ps) with engineering notation exponents (3, 6, 9, 12), | |
truncated to 2 decimal places. | |
Args: | |
seconds (float): Time in seconds | |
Returns: | |
str: Formatted time string with appropriate unit | |
Examples: | |
format_seconds(0.125) => "125.00 ms" | |
format_seconds(0.0000035) => "3.50 μs" | |
format_seconds(0.0000000078) => "7.80 ns" | |
""" | |
abs_seconds = abs(seconds) | |
if abs_seconds >= 1: | |
# seconds (10^0) | |
return f"{seconds:.2f} s" | |
if abs_seconds >= 0.001: | |
# milliseconds (10^-3) | |
return f"{seconds * 1000:.2f} ms" | |
elif abs_seconds >= 0.000001: | |
# microseconds (10^-6) | |
return f"{seconds * 1000000:.2f} μs" | |
elif abs_seconds >= 0.000000001: | |
# nanoseconds (10^-9) | |
return f"{seconds * 1000000000:.2f} ns" | |
else: | |
# picoseconds (10^-12) | |
return f"{seconds * 1000000000000:.2f} ps" | |
def main(): | |
# Test cases | |
test_values = [ | |
(1.0, "1.00 s"), | |
(0.1, "100.00 ms"), | |
(0.001, "1.00 ms"), | |
(0.0005, "500.00 μs"), | |
(0.0001, "100.00 μs"), | |
(0.000001, "1.00 μs"), | |
(0.0000005, "500.00 ns"), | |
(0.0000001, "100.00 ns"), | |
(0.000000001, "1.00 ns"), | |
(0.0000000005, "500.00 ps"), | |
(0.0000000001, "100.00 ps"), | |
(0.00000000001, "10.00 ps"), | |
(-0.0001, "-100.00 μs"), # Test negative numbers | |
] | |
print("Testing format_seconds function:") | |
print("-" * 40) | |
pass_count = 0 | |
fail_count = 0 | |
for value, expected in test_values: | |
result = format_seconds(value) | |
if result == expected: | |
status = "PASS" | |
pass_count = pass_count + 1 | |
else: | |
status = "FAIL" | |
fail_count = fail_count + 1 | |
print(f"Input: {value:.12f} seconds") | |
print(f"Result: {result}") | |
print(f"Expected: {expected}") | |
print(f"Status: {status}") | |
print("-" * 40) | |
print(f"PASSED = {pass_count}") | |
print(f"FAILED = {fail_count}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment