AttributeError: 模块'time'没有属性'clock'的解决方法

2,209 阅读3分钟

time.clock()方法已经在Python 3.8以上版本中被移除。因此,如果你正在使用 clock()方法,你会得到AttributeError: 模块 'time' 没有属性 'clock'。

在本教程中,我们将研究什么是AttributeError:模块'time'没有属性'clock',以及如何通过实例解决这个错误。

什么是AttributeError: module 'time' has no attribute 'clock'?

time.clock()方法从Python 3.8开始被废弃,如果在代码中使用,会导致AttributeError:模块'time'没有属性'clock'

如果你没有使用这个 clock()方法,但仍然面临这个错误,这意味着你正在使用一些Python库,如PyCrypto,sqlalchemy 等,这些库在内部使用了**time.clock()**方法。

让我们试着在Python 3.8中重现这个错误

import time

print(time.clock())

输出

AttributeError: module 'time' has no attribute 'clock'

如何解决 AttributeError: module 'time' has no attribute 'clock'?

有多种解决方案来解决这个AttributeError,解决方案取决于不同的用例。让我们来看看每个场景。

解决方案1 - 用time.process_time()和time.perf_counter()替换time.clock()。

我们可以使用其他的方法来代替 **time.clock()**方法,我们可以使用另一种方法,如 **time.perf_counter()**和 **time.process_time()**来代替方法,提供同样的结果。

让我们举个例子来看看如何实现这个方案。

该 **time.perf_counter()**函数返回一个以秒为单位的浮动时间值,即一个具有最高分辨率的时钟来测量一个短的时间。它确实包括睡眠期间的时间,并且是全系统的。

import time

# perf_counter includes the execution time and the sleep time
start_time = time.perf_counter()
time.sleep(4)
end_time = time.perf_counter()

print("Elapsed Time is ", end_time-start_time)

输出

Elapsed Time is  4.0122200999903725

该 **time.process_time()**方法将返回一个以秒为单位的时间浮点值。返回的时间将是当前进程的系统和用户CPU时间的总和。它不包括睡眠期间经过的时间。

import time

# perf_counter includes the execution time and the sleep time
start_time = time.process_time()
for i in range(1000):
    print(i, end=' ')
end_time = time.process_time()

print("Elapsed Time is ", end_time-start_time)

输出

Elapsed Time is  0.015625

解决方案2--将模块升级到最新版本

如果你在代码中直接使用 **time.clock()**方法,那么你所使用的一些外部模块将在内部使用它,因此你会得到这个错误。

如果你使用一个模块,如 SQLAlchemy的模块,请使用下面的命令将其升级到最新版本。

pip install <module_name> --upgrade
pip install SQLAlchemy --upgrade

解决方案3--用另一个替代的模块取代该模块

如果你使用的模块是像 替换为PyCrypto等模块,你就没有办法升级它,因为它没有被积极维护。

在这种情况下,你需要寻找一个像**PyCryptodome** 这样支持相同功能的替代模块。

# Uninstall the PyCrypto as its not maintained and install pycryptodome 
pip3 uninstall PyCrypto 
pip3 install pycryptodome 

解决方案 4 -- 降级 Python 版本

降级Python并不是一种推荐的方法。然而,如果你最近将Python版本升级到3.8 或以上,并面临这个问题,最好将其恢复或降级到以前的版本,直到你找到解决方案或实施上述任何解决方案。

结论

AttributeError: module 'time' has no attribute 'clock' occurs if you are using the time.clock() 方法的时候,就会出现这种错误。另一个原因可能是你正在使用一个外部模块,该模块内部使用 time.clock()函数。

我们可以通过使用替代的方法来解决这个问题,例如 time.process_time()time.perf_counter()方法。如果问题是由外部模块引起的,最好是升级该模块,或者在该模块没有提供修复方法的情况下找到一个替代模块。