Best timing method in C?

前端 未结 6 989
广开言路
广开言路 2020-11-28 18:55

What is the best way to time a code section with high resolution and portability?

/* Time from here */
ProcessIntenseFunction();
/* to here. */

printf(\"Tim         


        
6条回答
  •  忘掉有多难
    2020-11-28 19:13

    High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.

        #ifdef WIN32
          #ifndef PERFTIME
            #include 
            #include 
            #define PERFTIME_INIT unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  unsigned __int64 endTime;  double timeDifferenceInMilliseconds;
            #define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
            #define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);
        #define PERFTIME(funct) {unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq);  double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  QueryPerformanceCounter((LARGE_INTEGER *)&startTime);  unsigned __int64 endTime;  funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime);  double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);}
          #endif
        #else
          //AIX/Linux gettimeofday() implementation here
        #endif
    

    Usage:

    PERFTIME(ProcessIntenseFunction());
    
    or
    
    PERFTIME_INIT
    PERFTIME_START
    ProcessIntenseFunction()
    PERFTIME_END
    

提交回复
热议问题