May I ask what kind of processor you're using? If you're using an x86 processor, you can look at the time stamp counter (tsc
). This code snippet:
#define rdtsc(low,high) \
__asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
will put the number of cycles the CPU has run in low
and high
respectively (it expects 2 long
s; you can store the result in a long long int
) as follows:
inline void getcycles (long long int * cycles)
{
unsigned long low;
long high;
rdtsc(low,high);
*cycles = high;
*cycles <<= 32;
*cycles |= low;
}
Note that this returns the number of cycles your CPU has performed. You'll need to get your CPU speed and then figure out how many cycles per ns in order to get the number of ns elapsed.
To do the above, I've parsed the "cpu MHz" string out of /proc/cpuinfo
, and converted it to a decimal. After that, it's just a bit of math, and remember that 1MHz = 1,000,000 cycles per second, and that there are 1 billion ns / sec.