Get timestamp by rdtsc
Thursday, November 4, 2010 7:05:56 AM
On X86 processor, there is an instruction "rdtsc" to get a 64-bits width timestamp. This timestamp is set to 0 after processor reset.
The time-stamp value increases when processor running and processor families increment the time-stamp counter differently.
- For Pentium M processors (family [06H], models [09H, 0DH]); for Pentium 4 processors, Intel Xeon processors (family [0FH], models [00H, 01H, or 02H]); and for P6 family processors: the time-stamp counter increments with every internal processor clock cycle.
- For Pentium 4 processors, Intel Xeon processors (family [0FH], models [03H and higher]); for Intel Core Solo and Intel Core Duo processors (family [06H], model [0EH]); for the Intel Xeon processor 5100 series and Intel Core 2 Duo processors (family [06H], model [0FH]); for Intel Core 2 and Intel Xeon processors (family [06H], display_model [17H]); for Intel Atom processors (family [06H],display_model [1CH]): the time-stamp counter increments at a constant rate.That rate may be set by the maximum core-clock to bus-clock ratio of the processor or may be set by the maximum resolved frequency at which the processor is booted.
So if the timestamp increases at a constant rate, we can get the nanoseconds since processor
boot up.
uint32_t low;
uint32_t high;
uint64_t retval;
__asm__ volatile ("rdtsc\n" : "=a" (low), "=d" (high));
retval = high;
retval <<= 32;
retval = retval | low;
The time-stamp value increases when processor running and processor families increment the time-stamp counter differently.
- For Pentium M processors (family [06H], models [09H, 0DH]); for Pentium 4 processors, Intel Xeon processors (family [0FH], models [00H, 01H, or 02H]); and for P6 family processors: the time-stamp counter increments with every internal processor clock cycle.
- For Pentium 4 processors, Intel Xeon processors (family [0FH], models [03H and higher]); for Intel Core Solo and Intel Core Duo processors (family [06H], model [0EH]); for the Intel Xeon processor 5100 series and Intel Core 2 Duo processors (family [06H], model [0FH]); for Intel Core 2 and Intel Xeon processors (family [06H], display_model [17H]); for Intel Atom processors (family [06H],display_model [1CH]): the time-stamp counter increments at a constant rate.That rate may be set by the maximum core-clock to bus-clock ratio of the processor or may be set by the maximum resolved frequency at which the processor is booted.
So if the timestamp increases at a constant rate, we can get the nanoseconds since processor
boot up.
#define NANOSECONDS_PER_SECOND 1000000000
uint64_t freq = 2133 * 1000000; /* host processor's frequency */
static uint64_t nanoseconds_from_tsc(void)
{
uint32_t low;
uint32_t high;
uint64_t retval;
__asm__ volatile ("rdtsc\n" : "=a" (low), "=d" (high));
retval = high;
retval <<= 32;
retval = retval | low;
return (double) retval * NANOSECONDS_PER_SECOND / freq;
}













