Seconds calculation using rdtsc

2020-04-17 07:03发布

问题:

Here is the code to calculate CPU time but it's not correct because when I use gettimeofday it gives me correct time in ms. I am running my process on one processor and its clock runs at 800MHz. My knowledge about rdtsc is as follows:

  • Rdtsc returns number of cycles
  • Using those # of cycles one can calculate the CPU time given the clock rate (800 MHZ)

    unsigned long long a,b;
    unsigned long cpuMask;
    cpuMask = 2; // bind to cpu 1
    if(!sched_setaffinity(0, sizeof(cpuMask), &cpuMask))
    fprintf(stderr,"Running on one core!\n");
    setpriority(PRIO_PROCESS, 0, 20);
    struct timeval t1, t2;
    double elapsedTime;
    int i=0;
    // start timer
    gettimeofday(&t1, NULL);    
    a = rdtsc();
    sleep(20);      
    //for(;i<1000000;i++);
          //fprintf(stderr,"%d\n",i);
    gettimeofday(&t2, NULL);
    b = rdtsc();
    printf("a:%llu\n", a);
    printf("b:%llu\n", b);
    double val = ((b-a)/800000);        
    fprintf(stderr,"Time 1st through rdtsc in msec:%f\n\nSubtraction:%llu\n\n", val,b-a);
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
    fprintf(stderr,"Time through gettimeofday in ms:%f\n\n", elapsedTime);
    

回答1:

In theory, there is no guarantee that rdtsc would have strong relation to CPU cycles, e.g. 1 cycle may equal to 3 rdtsc units. In practice, rdtsc unit equals to (1 second / max_frequency_of_cpu) on Intel CPUs assuming constant_tsc feature is present. So, first question is: is 800MHz is max frequency or is it current frequency?

Anyway, clock_gettime(CLOCK_MONOTONIC_RAW, ...) is what most likely you want to use. My understanding is that it is mapped exactly to timestamp counter and is calibrated with system clock when OS is booted.

(And yes, your code works exactly as expected on my i7-3635QM).