Read CPU time consumed by the current process.
How It Works
time.process_time() measures user and system CPU time for the process and excludes most time spent sleeping. This differs from perf_counter(), which measures elapsed wall duration.
Step-by-Step Example
import time
start_cpu = time.process_time()
time.sleep(0.001)
end_cpu = time.process_time()
print(end_cpu >= start_cpu)
Understanding the Example
- The expression 'time.process_time()' supplies the value stored as 'start_cpu'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
Run the complete example as written, then inspect the displayed result. The values returned by the operation are more important than simply seeing the script finish.
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
CPU process time is not a calendar timestamp.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using process_time() to time network requests or sleep delays, which it intentionally excludes.
- Compare CPU-bound calculation time to sleep-heavy work.
Key Takeaways
- Read CPU time consumed by the current process.
- time.process_time() measures user and system CPU time for the process and excludes most time spent sleeping.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.