Python报错AttributeError:module 'time' has no attribute 'clock'如何解决?
解决
time.clock()引发的AttributeError问题 问题原因
Python 3.8及更高版本已移除time.clock()方法,调用该方法会触发AttributeError: module 'time' has no attribute 'clock'错误。
替代方案
根据计时需求选择以下两种替代方法:
- 测量CPU时间(进程占用的处理器时间):使用
time.process_time(),返回当前进程的系统CPU时间与用户CPU时间之和,单位为秒。
替换代码:start_time = time.process_time() - 测量实际流逝时间(墙钟时间):使用
time.perf_counter(),提供系统最高精度的计时器,适合测量短时间间隔。
替换代码:start_time = time.perf_counter()
补充说明
旧版time.clock()在不同系统行为不一致:Windows系统中测量墙钟时间,Unix系统中测量CPU时间。根据你的原始需求选择对应替代方法即可。
内容的提问来源于stack exchange,提问作者Natalya Br Sidauruk
相关产品推荐
相关产品推荐

