Learning & Discussion

- C/C++

- Linux: 在 Linux User Space 使用 TSC (x86 架構下)

TSC

The Time Stamp Counter (TSC) is a 64-bit timer register in Pentium-compatible processors that counts the number of clock cycles consumed by the processor. TSC provides a high-resolution timer and is commonly used for profiling and instrumenting code.

The count of ten millisecond jiffies is the primary means by which the original timer tracks time. Unfortunately, the assumed jiffy length is rarely correct, because the hardware timer chip has a finite resolution and the smallest value by which it can be incremented usually does not divide evenly into ten milliseconds. The accumulation of error due to the imprecision in the jiffy length causes the software clock to drift over time. However, TSC is more precise and hence lead to less clock drift. At each interrupt, a TSC reading is taken and used to compute the number of cycles elapsed since boot time.

TSC can be accessed using the rdtsc instruction to measure execution time of intervening code with microsecond precision. TSC ticks can be converted to seconds by dividing by the CPU clock speed, which can be read from the kernel variable, cpu_khz.


RDTSC

  • Instruction to read TSC in X86 assembly language.
  • The instruction returns a 64 bit value using 2 32-bit registers EDX:EAX.

Functions:

  • gettsc()
unsigned long long gettsc(void) {    //get TSC value from EDX:EAX
    unsigned long ax, dx;
    asm volatile("rdtsc" : "=a" (ax), "=d" (dx));
    return ((unsigned long long)dx << 32) + ax;
}
  • Convert Cycles to Time
unsigned long long gettsctime(unsigned long long tsc, unsigned 
long long *t) {    //tsc increments one unit by one clock cycle, so we get time by taking tsc divided by clock rate. 
    float mhz;
    unsigned long long tmp;
    mhz = getmhz();
    *t = (unsigned long long)((double)tsc/(double)mhz*1000);
}
  • getmhz()
    1. In Linux
    2. Parse /proc/cpuinfo to get CPU Mhz.

Example:

  • Time Measurement
void main()    //measure the elapsed time of "sleep(3)"
{
    unsigned long long tsc, start, end;
    tsc = gettsc();             //get tsc value
    gettsctime(tsc, &start);    //get time at the start of measured program interval
    sleep(3);                   //measured program interval
    tsc = gettsc();             //get tsc value
    gettsctime(tsc, &end);      //get time at the end of measured program interval
    gettscinterval(start, end); //get time interval of measured program
}
documents/tsc/tsc.txt · 上一次變更: 2008/08/31 22:38 由 crilit
CC Attribution-Noncommercial-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0