RDTSC

From Wikipedia, the free encyclopedia

In the x86 assembly language, the RDTSC instruction is a mnemonic for read time stamp counter. The instruction returns a 64-bit value in registers EDX:EAX that represents the count of ticks from processor reset. Added in Pentium. Opcode: 0F 31. This instruction was not formally part of the X86 assembly language at Pentium and was recommended for use by expert users or System Programmers only (Intel reference required). Pentium competitors such as the Cyrix 6x86 did not always have a TSC and may consider this instruction illegal. Use of this instruction in Linux distributions precludes Linux from booting where the CPU does not support RDTSC. Cyrix included a Time Stamp Counter in their MII CPU architecture as RTDSC was formally included in the X86 assembly language in Pentium II.

The RDTSC instruction has, until recently, been an excellent high-resolution, low-overhead way of getting CPU timing information. With the advent of multi-core/hyperthreaded CPUs, systems with multiple CPUs, and "hibernating" operating systems, RDTSC often no longer provides reliable results. The issue has two components: rate of tick and whether all cores (processors) have identical values in their time-keeping registers. There is no longer any promise that the timestamp counters of multiple CPUs on a single motherboard will be synchronized. So, you can no longer get reliable timestamp values unless you lock your program to using a single CPU. Even then, the CPU speed may change due to power-saving measures taken by the OS or BIOS, or the system may be hibernated and later resumed (resetting the time stamp counter). Also it makes the program not portable to anything other than x86.

Under Windows platforms, Microsoft strongly discourages using RDTSC for high-resolution timing for exactly these reasons, providing instead the Windows APIs QueryPerformanceCounter and QueryPerformanceFrequency.

Contents

[edit] Examples of using it

[edit] C

GNU C++

#include <stdint.h>
extern "C" {
__inline__ uint64_t rdtsc() {
  uint32_t lo, hi;
 /* We cannot use "=A", since this would use %rax on x86_64 */
  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  return (uint64_t)hi << 32 | lo;
}
}

Microsoft Visual C++

__declspec(naked)
unsigned __int64 __cdecl rdtsc(void)
{
   __asm
   {
      rdtsc
      ret       ; return value at EDX:EAX
   }
}

[edit] Pascal / Delphi

function RDTSC: comp;
var TimeStamp: record case byte of
                 1: (Whole: comp);
                 2: (Lo, Hi: Longint);
               end;
begin
  asm
    db $0F; db $31;
    mov [TimeStamp.Lo], eax
    mov [TimeStamp.Hi], edx
  end;
  Result := TimeStamp.Whole;
end;

In more recent versions of Delphi you can also use:

function RDTSC: Int64; register;
asm
  rdtsc
end;

[edit] FreeBASIC

 Function ReadTSC() As uLongInt
   Asm
     rdtsc
     mov [function], eax
     mov [function+4], edx
   End Asm
 End Function

[edit] References

In other languages