C++ 中的 clock_gettime() 和 python 中的 time.time() 等价吗?

Are clock_gettime() in C++ and time.time() in python equivalent?

我正在使用 boost python 并尝试测量从 C++ 切换到 python 的延迟时间,反之亦然。但我认为我做错了,我通过 clock_gettime()(t0) 在 C++ 中获取时间并将其作为参数传递给 python 函数并从内部传递这个函数我调用 time.time()(t1) 来获取时间。但是当我尝试通过 t1-t0 来测量延迟时,它有时为正,有时为负,有时为 0。这是为什么?

我希望这个延迟在纳秒级,所以如果你想测量它,使用准确的时钟并确保它们一致是很重要的。还要了解,在这个级别上实际读取时钟将是不可忽略的成本,因此它可能不是一个现实的目标。

对于python 3,底层C函数调用可用time.get_clock_info

在我的系统上,time.time() 使用 clock_gettime(CLOCK_REALTIME)

In [1]: import time
In [2]: time.get_clock_info("time")
Out[2]: namespace(adjustable=True, implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, resolution=1e-09)

对于您的目的来说这可能已经足够了,但是 time.perf_counter() 可以有更好的精度,尤其是在 windows.

如果您卡在 python 2,根据 source time.time() 尝试使用 gettimeofday(),然后是 ftime(),然后是 time()。由于 windows 没有 gettimeofday,它将使用 ftime 至多毫秒精度,而在 *nix 上,gettimeofday 只有微秒精度。

在 windows 上你可以使用 time.clock(),它使用 QueryPerformanceCounter(),但在 linux 上它使用 clock(),这也是通常只有微秒精度,所以也可能没有足够的精度。

您可以尝试不同的策略,并使用 clock_gettime 计算空 python 函数的完整执行时间,或者两次 python 调用 boost 包装器之间的差异clock_gettime(),这至少会得到一个上限。您还可以计时一百万个空函数调用或其他一些东西来消除查询时间的一些成本。