I am looking for a fast way to get the elapsed time between two calls of a function in C.
I considered using jiffies, but they are not available in userland. So, should I use getimeofday() or is there any fastest way to do this.
I am only interested in the elasped time between two calls, to use in a benchmark tool.
I'd get the processor time via
clock()
fromtime.h
. To get useful values, convert to milliseconds viaCLOCKS_PER_SEC
:If you're on an x86/x64 architecture, and you're running on a single CPU, you might consider reading the time-stamp counter on the CPU to get a cycle-count. Wikipedia has more information. Note that this approach is less useful if your application is running on multiple CPUs, since each CPU will have its own TSC. Also be wary of frequency scaling if you decide that you want to convert cycles -> time units.
If your kernel supports
gettimeofday()
as a vsyscall (virtual system call), then using this will be faster than calling a regular system call such asclock()
. See Andrea Arcangeli's presentation for some information on how vsyscalls work.The following works for me on CentOS 6:
...although it does require
librt
:Take a look at
clock_gettime
, which provides access to high-resolution timers.Bit of a late addition, however the time uility available on any linux/unix may be a lighter weight way of achieving what you want. Here are 2 examples