Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this code calculate the number of CPU cycles elapsed?

Tags:

c

cpu

cpu-cycles

Taken from this SO thread, this piece of code calculates the number of CPU cycles elapsed running code between lines //1 and //2.

$ cat cyc.c 
#include<stdio.h>

static __inline__ unsigned long long rdtsc(void)
{
  unsigned long long int x;
     __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
     return x;
}

int main() {
    unsigned long long cycles = rdtsc(); //1
    cycles = rdtsc() - cycles;           //2
    printf("Time is %d\n", (unsigned)cycles);
    return 0;
}

$ gcc cyc.c -o cyc
$ ./cyc
Time is 73
$ ./cyc
Time is 74
$ ./cyc
Time is 63
$ ./cyc
Time is 73
$

How does the rdtsc() function work?

like image 313
Lazer Avatar asked Oct 09 '10 22:10

Lazer


People also ask

How many cycles does an addition take in a CPU?

Because assembly instruction ADD only takes 1-2 CPU cycles.

What do you understand by CPU cycle?

CPU cycle Usually, the time required for the execution of one simple processor operation such as an addition; this time is normally the reciprocal of the clock rate.

What is Rdtsc C++?

RDTSC is short for “Read Time-Stamp Counter”. It returns the number of clock cycles since last reset. The modern complier Visual Studio has implemented the compiler intrinsic so you don't have to manually insert the assembly opcode (i.e. 0F 31) or mnemonic (RDTSC) into your C++ source code.


1 Answers

The function executes the x86 instruction RTDSC, which happens to have an opcode of 0x0f, 0x31. The processor keeps track of clock cycles internally, and this reads that number.

Of course, this only works on x86 procs, other processors will need different instructions.

The Time Stamp Counter is a 64-bit register present on all x86 processors since the Pentium. It counts the number of ticks since reset. Instruction RDTSC returns the TSC in EDX:EAX. Its opcode is 0F 31.[1] Pentium competitors such as the Cyrix 6x86 did not always have a TSC and may consider RDTSC an illegal instruction. Cyrix included a Time Stamp Counter in their MII.

http://en.wikipedia.org/wiki/Time_Stamp_Counter

like image 174
dsolimano Avatar answered Oct 08 '22 08:10

dsolimano