Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure time up to millisecond in Cython?

I have read this question, but I would like to get better timing precision than a second: is this possible with some function of libc?

This is to use inside with nogil, so of course no Python is allowed...

like image 319
P. Camilleri Avatar asked Nov 09 '22 01:11

P. Camilleri


1 Answers

You can use 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.)

This snippet store in current the number of seconds since epoch with up to a nanosecond precision (depending on your system).

You can also use gettimeofday(), but it is now deprecated:

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

like image 53
DurandA Avatar answered Nov 14 '22 20:11

DurandA