-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_duration.py
More file actions
50 lines (41 loc) · 1.26 KB
/
get_duration.py
File metadata and controls
50 lines (41 loc) · 1.26 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
"""
An example of how to measure the time it takes to run a section of code
"""
import time
import logging
logger = logging.getLogger(__name__)
def format_duration_long(duration_seconds: float) -> str:
"""
Format duration in a human-friendly way, showing only the two largest non-zero units.
For durations >= 1s, do not show microseconds or nanoseconds.
For durations >= 1m, do not show milliseconds.
"""
ns = int(duration_seconds * 1_000_000_000)
units = [
("y", 365 * 24 * 60 * 60 * 1_000_000_000),
("mo", 30 * 24 * 60 * 60 * 1_000_000_000),
("d", 24 * 60 * 60 * 1_000_000_000),
("h", 60 * 60 * 1_000_000_000),
("m", 60 * 1_000_000_000),
("s", 1_000_000_000),
("ms", 1_000_000),
("us", 1_000),
("ns", 1),
]
parts = []
for name, factor in units:
value, ns = divmod(ns, factor)
if value:
parts.append(f"{value}{name}")
if len(parts) == 2:
break
if not parts:
return "0s"
return "".join(parts)
start_ns = time.perf_counter_ns()
print("Start")
time.sleep(1)
print("End")
end_ns = time.perf_counter_ns()
duration_s = (end_ns - start_ns) / 1e9
print(f"Execution completed in {format_duration_long(duration_s)}.")