How to calculate the execution time in C?

后端 未结 4 1265
自闭症患者
自闭症患者 2021-01-27 09:38

How can I calculate the execution time in the following code:

#include   /* Core input/output operations                         */
#include 

        
4条回答
  •  清歌不尽
    2021-01-27 10:16

    Try this:

    printf("    Time   : %lu\n", clock() );
    printf("    Start Time   : %lds %ldus\n", tv1.tv_sec, tv1.tv_usec);
    printf("    End Time   : %lds %ldus\n", tv2.tv_sec, tv2.tv_usec);
    

    And for:

    double timeval_subtract (result, x, y)
    

    use the following to return the time difference in micro seconds:

    long timeval_subtract (struct timeval * result, struct timeval * x, struct timeval * y)
    {
       long usec = x->tv_sec * 1000000L + x->tv_usec;
       usec -= (y->tv_sec * 1000000L + y->tv_usec);
    
       result->tv_sec = usec / 1000000L;
       result->tv_usec = usec % 1000000L;
    
       return usec;
    }
    

    Depending on the difference of the two dates x and y the return value of the function timeval_subtract (not the value represented by result!) might be wrong, due to an overflow.

    Assuming a long is 32bit wide this overflow will occur with differences larger than 4294s, for a long having 64bit (which should be the case an 64bit machines) the overflow whould occur after much later ... ;-)

提交回复
热议问题