在Python中使用哪个更好?Time.clock()还是time.time()?哪一种更准确?
例如:
start = time.clock()
... do something
elapsed = (time.clock() - start)
vs.
start = time.time()
... do something
elapsed = (time.time() - start)
在Python中使用哪个更好?Time.clock()还是time.time()?哪一种更准确?
例如:
start = time.clock()
... do something
elapsed = (time.clock() - start)
vs.
start = time.time()
... do something
elapsed = (time.time() - start)
当前回答
正如其他人所注意到的,time.clock()已被弃用,取而代之的是time.perf_counter()或time.process_time(),但Python 3.7通过time.perf_counter_ns()、time.process_time_ns()和time.time_ns()以及其他3个函数引入了纳秒分辨率计时。
PEP 564中详细介绍了这6个新的纳秒分辨率函数:
time.clock_gettime_ns (clock_id) 时间。clock_settime_ns (clock_id、时间:int) time.monotonic_ns () time.perf_counter_ns () time.process_time_ns () time.time_ns () 这些函数类似于没有_ns后缀的版本,但是 返回一个纳秒数作为Python int。
正如其他人也注意到的那样,使用timeit模块为函数和小代码段计时。
其他回答
这取决于你在乎什么。如果您指的是WALL TIME(即墙上时钟上的时间),则TIME .clock()不能提供精度,因为它可能管理CPU时间。
time.clock()在Python 3.8中被移除,因为它具有平台相关的行为:
在Unix上,返回以秒表示的浮点数形式的当前处理器时间。 在Windows上,此函数以浮点数的形式返回自第一次调用该函数以来经过的时钟秒数 打印(time.clock ());time . sleep (10);print (time.clock ()) # Linux: 0.0382 0.0384 #参见处理器时间 # Windows: 26.1224 36.1566 #见clock Time
那么选择哪个函数呢?
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this. Use time.process_time() Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time. Use time.perf_counter() time.time() also measures wall-clock time but can be reset, so you could go back in time time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
正如其他人所注意到的,time.clock()已被弃用,取而代之的是time.perf_counter()或time.process_time(),但Python 3.7通过time.perf_counter_ns()、time.process_time_ns()和time.time_ns()以及其他3个函数引入了纳秒分辨率计时。
PEP 564中详细介绍了这6个新的纳秒分辨率函数:
time.clock_gettime_ns (clock_id) 时间。clock_settime_ns (clock_id、时间:int) time.monotonic_ns () time.perf_counter_ns () time.process_time_ns () time.time_ns () 这些函数类似于没有_ns后缀的版本,但是 返回一个纳秒数作为Python int。
正如其他人也注意到的那样,使用timeit模块为函数和小代码段计时。
Clock() ->浮点数
返回CPU时间或进程启动后的实时时间 第一次调用clock()。这和系统的精度一样高 记录。
Time() ->浮点数
返回当前时间(以秒为单位)。 如果系统时钟提供,可能会出现几分之一秒。
通常time()更精确,因为操作系统存储进程运行时间的精度与存储系统时间(即实际时间)的精度不同。
简单的答案是:大多数时候time.clock()会更好。 然而,如果你正在为某些硬件计时(例如你在GPU中放入的某些算法),那么time.clock()将摆脱这个时间,而time.time()是唯一剩下的解决方案。
注意:无论使用何种方法,计时将取决于您无法控制的因素(进程何时切换,频率如何,……),这对于time.time()来说更糟糕,但对于time.clock()也存在,因此您永远不应该只运行一个计时测试,而是始终运行一系列测试并查看时间的均值/方差。