I'm trying to time how long a sort function takes, but I am struggling getting time.process_time()
to work.
My current setup is:
start = time.process_time()
insertionsort(n)
end = time.process_time()
time = start-end
When I run this, I am getting this error:
'float' object has no attribute 'process_time'
How do I fix this problem? I want to use time.process_time()
.
The issue is in a part of the code that you didn't show. I assume that you imported the time
module in the beginning:
import time
Which creates a name time
that references the time
module.
But later you create a variable named time
that stores the time difference. At that point the name time
references the difference and not the module. So when you try to use time.process_time()
afterwards you get the Error.
This simple snippet illustrates the problem:
>>> import time
>>> time = -(time.process_time() - time.process_time())
>>> time.process_time()
AttributeError: 'float' object has no attribute 'process_time'
If you insist on using time.process_time()
the best way around would be to rename the variable that stores the time difference:
measured_execution_time_insertionsort = end - start
But you could also import the process_time
function from the time
module directly:
from time import process_time
start = process_time()
insertionsort(n)
end = process_time()
time = end - start
Both approaches avoid the name clash. However I would recommend you use the timeit
module if you want to measure executions times, it's better suited for this kind of task than the time
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With