Solving AttributeError: module ‘time’ has no attribute ‘clock’ in Python

AttributeError: module ‘time’ has no attribute ‘clock’ is an error which happens in Python 3 when the function time.clock() is used.

In this article I am going to explain why the error is occurring and how to solve it using multiple solutions which may work for your particular case.

Describing AttributeError: module ‘time’ has no attribute ‘clock’ in Python

The error is occurring because the function time.clock() has been removed from Python versions 3.3 and above.

The error can happen in any code written in Python 3.3 or above. Here is an example of how the error message looks like.

                                                                       #
Traceback (most recent call last):
  File "temp.py", line 18, in <module>
    a = generate_keys()
  File "temp.py", line 8, in generate_keys
.
.
    value = getRandomInteger(bits, randfunc)
    X = getRandomRange (lower_bound, upper_bound, randfunc)
.
.
    t = time.clock()
AttributeError: module 'time' has no attribute 'clock'
                                                                       #

Bellow we will take care of the error using multiple possible solutions according to your needs.

Solution 1 : use the function time.process_time()

The function has been removed from most versions of Python 3. The function should be replaced in your code by other functions which can help you achieve the same results you wanted to get with the function time.clock().

An obvious choice is using the function time.process_time() instead.

This function will give you the duration a process spends while being executed on the CPU of the user’ s machine. The wait and sleep time are not included in this count.

Simple, just replace time.clock() in your code with time.process_time().

Solution 2 : use the function time.time()

The second solution is to use the function time.time() instead.

time.time() is just a function which measures time, just like a clock on the wall. The good thing about this function is that you can reset the time, which as far as I know, cannot be done on the other functions.

Again, the solution is very simple, just replace time.clock() with time.time() in your code. And as a result the error should be gone.

Summing-up

This error can be confusing but the fix is actually simple, the error is a matter of Python version and the attributes and functions that have been removed, keep coding guys and cheers.