Skip to content
Advertisement

Fast method to get current time with nsec-resolution?

I try to get a time-information with a resolution of a few hundred nanoseconds (to do some bit-banging stuff on an Raspberry Pi). I tried with clock_gettime() which provides the required resolution in timespec.tv_nsec, but it is too slow. Even when I run my process on one separate core of the CPU exclusively and even when I set this process to highest priority, the whole time measurement loop needs about 450 nsec where about 360 nsec are used by the function clock_gettime().

So my question: is there a way to faster retrieve the current time? Any other time-function? Or would it be a solution to use a kernel-module instead of a user space process?

Advertisement

Answer

Probably not. clock_gettime() is already implemented through the vDSO, so it’s likely to be the fastest possible system call there is.

But consider the timescales involved. With a 2 GHz processor, 450 nanoseconds is only 900 clock cycles. That’s not very much.

On one 1,86 GHz Core 2 machine, running just clock_gettime() in a loop returns values that are 86 ns apart. Just adding a filler of for (int j = 0 ; j < 100 ; j++); increases that to 540 ns. (about 4,5 ns per loop iteration, or around 8-9 clock cycles)

There’s not much you can you do in that time. What you can do, is to count clock cycles, or loop iterations. Use clock_gettime() beforehand to determine how much time a busyloop of N iterations requires on that machine, and then scale the number of iterations to get a timing loop of a required length.

You’re probably still going to need some time when doing the actual bit-flipping, assuming it goes through a system call. A kernel module might be useful there, in that you could avoid the system call overhead. Inside the kernel, it might also be easier to prevent the code from being pre-empted while working on the bit-banging.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement