我还需要计算一些代码行的处理时间。所以我尝试了批准的答案,我收到了这个警告。
DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
所以 python 将从Python 3.8 转换为remove time.clock()。您可以从问题#13270 中了解更多信息。此警告建议使用两个函数而不是 time.clock()。在文档中还详细提到了time.clock() 部分中的此警告。
自 3.3 版起已弃用,将在 3.8 版中删除:此函数的行为取决于平台:根据您的要求使用 perf_counter() 或 process_time() 来获得明确定义的行为。
让我们详细了解这两个函数。
返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟以测量短持续时间。它确实包括睡眠期间经过的时间,并且是系统范围的。返回值的参考点是未定义的,所以只有两次调用结果的差异才有效。
3.3 版中的新功能。
在 3.10 版中更改:在 Windows 上,该功能现在是系统范围的。
所以如果你想要它为nanoseconds,你可以使用time.perf_counter_ns(),如果你的代码与time.sleep(secs)一致,它也将被计算在内。例如:-
import time
def func(x):
time.sleep(5)
return x * x
lst = [1, 2, 3]
tic = time.perf_counter()
print([func(x) for x in lst])
toc = time.perf_counter()
print(toc - tic)
# [1, 4, 9]
# 15.0041916 --> output including 5 seconds sleep time
返回当前进程的系统和用户 CPU 时间之和的值(以秒为单位)。它不包括睡眠期间经过的时间。根据定义,它是进程范围的。返回值的参考点是未定义的,所以只有两次调用结果的差异才有效。
使用process_time_ns()避免float类型造成的精度损失。
3.3 版中的新功能。
因此,如果您希望它为nanoseconds,则可以使用time.process_time_ns(),如果您的代码与time.sleep(secs) 一致,则不会计算在内。例如:-
import time
def func(x):
time.sleep(5)
return x * x
lst = [1, 2, 3]
tic = time.process_time()
print([func(x) for x in lst])
toc = time.process_time()
print(toc - tic)
# [1, 4, 9]
# 0.0 --> output excluding 5 seconds sleep time
请注意time.perf_counter_ns() 和time.process_time_ns() 都想出Python 3.7。