如何在 Cython 中测量毫秒级的时间?

How to measure time up to millisecond in Cython?

我已阅读 this question,但我希望获得比秒更好的计时精度:这可以通过 libc 的某些功能实现吗?

这是在with nogil里面使用,所以当然不允许Python...

你为什么不使用日期时间?例如 datetime.datetime.now() 将为您提供当前时间值,包括毫秒。

您可以使用 POSIX clock_gettime():

from posix.time cimport clock_gettime, timespec, CLOCK_REALTIME

cdef timespec ts
cdef double current
clock_gettime(CLOCK_REALTIME, &ts)
current = ts.tv_sec + (ts.tv_nsec / 1000000000.)

此代码段以纳秒精度(取决于您的系统)在 current 中存储自纪元以来的秒数。

您也可以使用 gettimeofday(),但现在已弃用:

POSIX.1-2008 marks gettimeofday() as obsolete, recommending the use of clock_gettime(2) instead.