The time
module in python3 is used to provide various time-related functions.
We will discuss the major differences and use cases of the time.perf_counter()
and time.process_time()
.
time.perf_counter(): float
Returns the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
We can use perf_counter_ns()
to avoid the precision loss caused by the float
type.
Here is an example of how to use time.perf_counter()
:
import time
def my_function():
# Do some work here
start = time.perf_counter()
my_function()
end = time.perf_counter()
elapsed_time = end - start
print(f"Elapsed time for my_function(): {elapsed_time}")
time.process_time(): float
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use process_time_ns()
to avoid the precision loss caused by the float
type.
Here is an example of how to use time.process_time()
:
import time
def factorial(n):
# Do some work here
start_time = time.process_time()
factorial(10)
end_time = time.process_time()
elapsed_time = end_time - start_time
print("Elapsed time:", elapsed_time)
Example
import time
def pc():
start = time.perf_counter()
time.sleep(1)
print(time.perf_counter()-start)
def pt():
start = time.process_time()
time.sleep(1)
print(time.process_time()-start)
pc() # 0.99872320449432
pt() # 0.0
Major Differences
Feature | perf_counter() | process_time() |
What it measures | Time since the program started | Time spent by the current process executing code |
Precision | More precise | Less precise |
Affected by system load | Yes | No |