time.process_time() function returns the CPU time used by the current process in seconds. It measures only the time during which the CPU executes the program and does not include sleep time or waiting for I/O operations. It is mainly used for benchmarking CPU-intensive tasks.
Example: In this example, CPU time is measured before and after a computation to calculate execution time. (Output may vary depending on system performance.)
import time
s = time.process_time()
t = 0
for i in range(1, 1000000):
t += i
e = time.process_time()
print(e - s, "seconds")
Output
0.223359418 seconds
Explanation:
- time.process_time() records CPU start time in s.
- Computation runs inside the loop.
- e - s gives CPU time used by the process.
Syntax
time.process_time()
- Parameters: No parameters.
- Return: Returns CPU time used by the current process as a floating-point number (in seconds).
Examples
Example 1: In this example, CPU time is measured for executing a function.
import time
def f():
return sum(range(1000000))
s = time.process_time()
f()
e = time.process_time()
print(e - s, "seconds")
Output
0.035399988 seconds
Explanation:
- s = time.process_time() records start time.
- f() executes computation.
- e - s gives CPU time taken by the function.
Example 2: Here, CPU time of a built-in function is compared with a manual loop.
import time
s = time.process_time()
sum(range(1000000))
e = time.process_time()
print("Built-in:", e - s)
s = time.process_time()
t = 0
for i in range(1000000):
t += i
e = time.process_time()
print("Loop:", e - s)
Output
Built-in: 0.02539901 Loop: 0.14826791699999997
Explanation:
- sum(range(...)) executes faster.
- Manual loop takes more CPU time.
- e - s shows performance difference.
Example 3: In this example, CPU time is measured for repeated execution of a task.
import time
s = time.process_time()
for _ in range(5):
sum(range(1000000))
e = time.process_time()
print("CPU Time:", e - s)
Output
CPU Time: 0.11963688
Explanation:
- Loop runs computation multiple times.
- time.process_time() measures total CPU usage.
- e - s gives total CPU time for all iterations.
time.process_time() vs time.time()
Both functions are used to measure time in Python, but they serve different purposes. One measures CPU execution time, while the other measures real-world elapsed (wall-clock) time.
| Feature | time.process_time() | time.time() |
|---|---|---|
| Measures | CPU execution time | Wall-clock (real) time |
| Includes sleep time | No | Yes |
| Includes I/O wait time | No | Yes |
| Affected by system clock changes | No | Yes |
| Suitable for | Benchmarking CPU-intensive tasks | Measuring real-world elapsed time |
| Return type | Float (seconds) | Float (seconds since epoch) |