clock() precision in time.h

前端 未结 4 1678
[愿得一人]
[愿得一人] 2020-12-09 22:22

I am trying to calculate the number of ticks a function uses to run and to do so an using the clock() function like so:

unsigned long time = clo         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 22:48

    The most precise (but highly not portable) way to measure time is to count CPU ticks.

    For instance on x86

     unsigned long long int asmx86Time ()
     {
       unsigned long long int realTimeClock = 0;
       asm volatile ( "rdtsc\n\t"         
                      "salq $32, %%rdx\n\t"    
                      "orq %%rdx, %%rax\n\t"   
                      "movq %%rax, %0"         
                      : "=r" ( realTimeClock ) 
                      : /* no inputs */
                      : "%rax", "%rdx" );
       return realTimeClock;
     }
    
     double cpuFreq ()
     {
       ifstream file ( "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" );
       string sFreq; if ( file ) file >> sFreq;
       stringstream ssFreq ( sFreq ); double freq = 0.;
       if ( ssFreq ) { ssFreq >> freq; freq *= 1000; } // kHz to Hz
       return freq;
     }
    
     // Timing
    
     unsigned long long int asmStart = asmx86Time ();
     doStuff ();
     unsigned long long int asmStop  = asmx86Time ();
     float asmDuration = ( asmStop - asmStart ) / cpuFreq ();
    

    If you don't have an x86, you'll have to re-write the assembler code accordingly to your CPU. If you need maximum precision, that's unfortunatelly the only way to go... otherwise use clock_gettime().

提交回复
热议问题