Python CPU 时钟。 time.clock() 对比 time.perf_counter() 对比 time.process_time()

Python CPU Clock. time.clock() vs time.perf_counter() vs time.process_time()

我想测量我的代码部分的长度 运行。我需要它是确定性的,这样我每次都能获得相同的持续时间 (seconds/milliseconds/etc),而不管后台发生了什么。所以我想在 unix 上使用 time.clock() 来测量 CPU 时间。

time.clock() 已被弃用,建议切换到 perf_counter 或 process_time。我正在查看 python 文档并发现以下内容。

time.perf_counter() → float Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

time.process_time() → float Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

因为我没有在我的代码中使用任何形式的睡眠,主要区别似乎是 'process-wide' 和 'system-wide'。可以详细说明一下区别吗?

其次,这是正确的做法吗?

perf_counter 和 timeit 都会为您提供测试代码块执行所需的时间。

time.process_time() 它不计算 CPU 所采用的内容,这不一定与函数或代码块相同。

我在 Github 上发现了这个话题,似乎这个问题很高级,并且可能完全不同,具体取决于 OS 或要进行基准测试的程序。

Something that time.process_time() is not counting is the Parent Multi-thread:

“使用 time.process_time 的一个后果是不包括在基准测试的子进程中花费的时间。多线程基准测试还 return 总 CPU 时间计算所有 CPUs."

perf_counter

from time import perf_counter


start = perf_counter()

for _ in range(10000):
    x = "-".join(str(n) for n in range(100))
end = perf_counter()
print('Perf Counter= ', end-start)
# Perf Counter=  0.23170840000000004

时间

import timeit

print(timeit.timeit('"-".join(str(n) for n in range(100))', number=10000))
# 0.20687929999999993