Python异常问题1:AttributeError module ‘time‘ has no attribute ‘clock‘

在pycharm中运行Python3.11环境之前,调用time.clock是正常的。后来升级到Python3.11的版本后提示异常:AttributeError module ‘time’ has no attribute ‘clock’
搜了度娘才知道,Python3.8之后的版本不再支持time.clock(),我们可以把time.clock()替换成time.perf_counter(),就能得到解决。作用都是一样的。

例如,以下运行是异常错误:

import time
scale = 50
print("执行开始".center(scale//2,'-'))
t = time.clock()
for i in range(scale + 1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    t -= time.clock()
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\
          end='')
    time.sleep(0.05)
print("\n"+"执行结束".center(scale/2,'-'))

替换方法如下,运行成功:

import time
scale = 50
print("执行开始".center(scale//2,'-'))
t = time.perf_counter()
for i in range(scale + 1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    t -= time.perf_counter()
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\
          end='')
    time.sleep(0.05)
print("\n"+"执行结束".center(scale/2,'-'))

你可能感兴趣的:(python,python)