Working with time.process_time()

12,524

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.

Share:
12,524
Brian Scalabrine of R
Author by

Brian Scalabrine of R

Updated on June 05, 2022

Comments

  • Brian Scalabrine of R
    Brian Scalabrine of R almost 2 years

    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().

    • Amit Tripathi
      Amit Tripathi over 6 years
      This is the issue. time = start-end don't name your variable with the same name as standard library.
  • Thomas S.
    Thomas S. almost 4 years
    To get a positive time answer will you need to make it time = end - start instead of time = start - end
  • MSeifert
    MSeifert almost 4 years
    @ThomasS. Yeah, I originally copied that from the question. However having a positive result seems obviously correct so I updated the answer. Thanks for pointing this out.
  • Nike
    Nike over 2 years
    After running import time and time = -(time.process_time() - time.process_time()) I get Traceback (most recent call last): File "<stdin>", line 1, in <module>. Maybe because I'm using Python 2.7.12 (default, Mar 1 2021, 11:38:31)? If I try to do from time import process_time I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name process_time
  • MSeifert
    MSeifert over 2 years
    @user1271772 Yeah, it's because you are using Python 2. That feature isn't implemented there.