#include #include #include #if !defined(__GNUC__) && !defined(__i386__) #error This code only works with GCC/i386. #endif /* The reason this only works under GNU C and the x86 is we're using the * rdtsc instruction. */ static inline unsigned long long rdtsc() { unsigned long long rval; asm volatile ("rdtsc" : "=A" (rval)); return rval; } static inline unsigned long read_and_clear(unsigned long * ptr) { unsigned long rval; asm volatile ("lock xchgl %0, %1" : "=r" (rval), "+m" (*ptr) : "0" (0)); return rval; } int main(void) { int i; volatile unsigned long trash; unsigned long val = 1; unsigned long long start, stop, time, min; /* Time how long a rdtsc takes- we do this ten times and take the * cheapest run. */ min = ~0ull; for (i = 0; i < 10; ++i) { start = rdtsc(); trash = 0; stop = rdtsc(); time = stop - start; if (time < min) { min = time; } } printf("Minimum time for a rdtsc instruction (in clocks): %llu\n", min); min = ~0ull; for (i = 0; i < 10; ++i) { val = 1; start = rdtsc(); trash = read_and_clear(&val); stop = rdtsc(); time = stop - start; if (time < min) { min = time; } } printf("Minimum time for a read_and_clear() + rdtsc (in clocks): %llu\n", min); return 0; }