Mac和Windows中Python的time.clock()有什么区别?

1 投票
2 回答
810 浏览
提问于 2025-04-18 17:20

我正在使用Python的时间功能来测量一个Selenium过程的时间。我的脚本是这样的...

start_time = time.clock()
...
#ending with
final_time = '{0:.2f}'.format(time.clock()-start_time)

在Windows系统上运行时,我会得到类似55.22的结果,但在Mac上运行时却只返回.14,尽管这两个过程的时间差不多。

你知道在Mac上发生了什么不同的情况吗?我其实也打算在Ubuntu上试试,看看有什么区别。

2 个回答

2

标准库中的timeit模块使用timeit.default_timer来测量实际经过的时间:

if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

help(timeit)可以给你解释:

The difference in default timer function is because on Windows,
clock() has microsecond granularity but time()'s granularity is 1/60th
of a second; on Unix, clock() has 1/100th of a second granularity and
time() is much more precise.  On either platform, the default timer
functions measure wall clock time, not the CPU time.  This means that
other processes running on the same computer may interfere with the
timing.  The best thing to do when accurate timing is necessary is to
repeat the timing a few times and use the best time.  The -r option is
good for this; the default of 3 repetitions is probably enough in most
cases.  On Unix, you can use clock() to measure CPU time.

所以为了在不同平台上保持一致,你可以使用

import timeit
clock = timeit.default_timer

start_time = clock()
...
final_time = clock()
6

根据文档的说明,time.clock在Unix(包括Mac OS X)和Windows上是不同的:

在Unix系统上,这个函数会返回当前处理器的时间,以浮点数的形式表示,单位是秒。这个时间的精确度,以及“处理器时间”的具体定义,取决于同名的C语言函数。不过无论如何,这个函数适合用来测试Python的性能或者计时算法。

而在Windows系统上,这个函数返回的是自第一次调用这个函数以来经过的实际时间(也就是墙钟时间),同样以浮点数的形式表示,基于Win32的QueryPerformanceCounter()函数。通常情况下,它的精度可以达到微秒级别。

如果你想要在不同平台上得到一致的结果,可以考虑使用time.time

关于处理器时间墙钟时间之间的区别,可以参考这篇Doug Hellmann的文章 - 基本上,处理器时钟只有在你的程序在运行时才会增加。

撰写回答