在Python 3.3之后,time.clock()
函数被弃用,并且在Python 3.8中已被完全移除。取而代之的是使用time.perf_counter()
或time.process_time()
函数来替代。
time.perf_counter()
函数返回一个性能计数器的值,该值在不同平台上有所不同,但具有单调递增的特性。在计算运行时间时,可以使用它来取代time.clock()
。下面是一个示例代码:
import time
start_time = time.perf_counter()
# 执行一些代码
end_time = time.perf_counter()
execution_time = end_time - start_time
print("代码执行时间:", execution_time, "秒")
另一个替代方案是使用time.process_time()
函数,它返回当前进程的CPU时间。与time.perf_counter()
不同,它不会包括休眠时间。下面是一个示例代码:
import time
start_time = time.process_time()
# 执行一些代码
end_time = time.process_time()
execution_time = end_time - start_time
print("代码执行时间:", execution_time, "秒")
这些替代方案可以根据具体的需求来选择。在计算代码的执行时间时,建议使用time.perf_counter()
函数,因为它更精确,并且在不同平台上表现一致。