Can someone help me understand how process_time() works? My code is
from time import process_time
t = process_time()
def fibonacci_of(n):
if n in cache: # Base case
return cache[n]
# Compute and cache the Fibonacci number
cache[n] = fibonacci_of(n - 1) fibonacci_of(n - 2) # Recursive case
return cache[n]
cache = {0: 0, 1: 1}
fib = [fibonacci_of(n) for n in range(1500)]
print(fib[-1])
print(process_time() - t)
And last print is always 0.0. My expected result is something like 0.764891862869 Docs at https://docs.python.org/3/library/time.html#time.process_time don't help newbie me :(
I tried some other functions and reading docs. But without success.
CodePudding user response:
I'd assume this is OS dependent. Linux lets me get down to ~5 microseconds using process_time
, but other operating systems might well not deal well with differences this small and return zero instead.
It's for this reason that Python exposes other timers that are designed to be more accurate over shorter time scales. Specifically, perf_counter
is specified as using:
the highest available resolution to measure a short duration
Using this lets me measure down to ~80 nanoseconds, whether I'm using perf_counter
or perf_counter_ns
.
CodePudding user response:
As documentation suggests:
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.
This last sentence is the most important and differentiates between the very precise function: process_time_ns()
and one that is less precise but more appropriate for the long-running processes - time.process_time()
.
It turns out that when you measure a couple nanoseconds (nano means 10**-9
) and try to express it in seconds dividing by 10**9
, you often go out of the precision of float
(64 bits) and end up rounding up to zero. The float limitations are described in the Python documentation.
To get to know more you can also read a general introduction to precision in floating point arithmetic (ambitious) and its peril (caveats).