首页 > 文章列表 > python time.clock()的出错解决

python time.clock()的出错解决

Python time.clock
154 2022-08-07

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、错误说明

弃用警告:时间时钟在python3.3中已被弃用,并将从python3.8:使用time.perf_counter或 time.process_time 而不是time.clock()。

#e6.1CalPi.py
from random import random
from math import sqrt
from time import clock
DARTS = 1000
hits = 0.0
clock()  #旧版本调用time.clock是没问题的  
for i in range(1, DARTS+1):
    x, y = random(), random()
    dist = sqrt(x ** 2 + y ** 2)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("Pi值是{}.".format(pi))
print("运行时间是: {:5.5}s".format(clock()))

2、解决办法

perf_counter的使用方法。

from time import perf_counter
def timer_2(f):
    def _f(*args):
        t0 = perf_counter()
        f(*args)
        return perf_counter() - t0
return _f

对于time.clock()的使用,随着python版本的更新而逐渐消失。有些人忽略了其使用环境而出现了报错,那么遇到这种情况,我们也有对应的解决方法。虽然新版本已经不支持这种函数的使用,但同样给出了另外两种函数用于替代。