A Python program can spend time executing on the CPU, waiting for I/O, or sleeping. Choose a clock that measures the quantity you actually need.
Measure elapsed time
For the duration of an operation, use
time.perf_counter() and subtract two readings:python_snippet
Python · 6 lines|
| import time |
| start = time.perf_counter() |
| time.sleep(1) # Replace with the operation being measured. |
| elapsed = time.perf_counter() - start |
| print(f"Elapsed: {elapsed:.3f} seconds") |
Elapsed time includes sleep and waiting. Only differences between readings are meaningful.
Measure process CPU time
python_snippet
Python · 5 lines|
| import time |
| start = time.process_time() |
| result = sum(range(1_000_000)) |
| print(f"CPU time: {time.process_time() - start:.6f} seconds") |
process_time() measures CPU time used by the current process and excludes sleep. It is not necessarily equal to elapsed time; multi-threaded CPU usage can also accumulate across threads.Wall-clock timestamps
time.time() returns seconds since the Unix epoch, and datetime.now() gives a calendar timestamp. They are useful for timestamps but system clock adjustments can affect duration measurements. When subtracting datetime values, use delta.total_seconds() rather than delta.seconds, which excludes whole days.The old
time.clock() API was platform-dependent and was removed in Python 3.8. Use perf_counter() for elapsed duration or process_time() for process CPU time.✦ 卷终 · 柯航存卷 ✦