Calculating Function time in nanoseconds in C code

前端 未结 4 1206
栀梦
栀梦 2020-12-19 07:29

I need to know how can I calculate the time of a function in C code in nanoseconds. I tried to repeat the function until consume some microseconds. Are there any other funct

4条回答
  •  心在旅途
    2020-12-19 07:48

    Regardless of how you approach this or what type of system/OS you are using, you are getting an approximate answer at best, with considerable variance due to the nature of the problem.

    Second, you need a system that supports this kind of call. It's pretty easy if you're using QNX Neutrino:

    http://www.qnx.com/developers/docs/6.3.0SP3/neutrino/lib_ref/c/clock_gettime.html

    /*
     * This program calculates the time required to
     * execute the program specified as its first argument.
     * The time is printed in seconds, on standard out.
     */
    #include 
    #include 
    #include 
    #include 
    
    #define BILLION  1000000000L;
    
    int main( int argc, char** argv )
      {
        struct timespec start, stop;
        double accum;
    
        if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
          perror( "clock gettime" );
          return EXIT_FAILURE;
        }
    
        system( argv[1] );
    
        if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
          perror( "clock gettime" );
          return EXIT_FAILURE;
        }
    
        accum = ( stop.tv_sec - start.tv_sec )
                 + (double)( stop.tv_nsec - start.tv_nsec )
                   / (double)BILLION;
        printf( "%lf\n", accum );
        return EXIT_SUCCESS;
      }
    

提交回复
热议问题