How can I benchmark C code easily?

前端 未结 4 1021
春和景丽
春和景丽 2020-11-27 11:58

Is there a simple library to benchmark the time it takes to execute a portion of C code? What I want is something like:

int main(){
    benchmarkBegin(0);
           


        
4条回答
  •  一个人的身影
    2020-11-27 12:25

    Basically, all you want is a high resolution timer. The elapsed time is of course just a difference in times and the speedup is calculated by dividing the times for each task. I have included the code for a high resolution timer that should work on at least windows and unix.

    #ifdef WIN32
    
    #include 
    double get_time()
    {
        LARGE_INTEGER t, f;
        QueryPerformanceCounter(&t);
        QueryPerformanceFrequency(&f);
        return (double)t.QuadPart/(double)f.QuadPart;
    }
    
    #else
    
    #include 
    #include 
    
    double get_time()
    {
        struct timeval t;
        struct timezone tzp;
        gettimeofday(&t, &tzp);
        return t.tv_sec + t.tv_usec*1e-6;
    }
    
    #endif
    

提交回复
热议问题