C - gettimeofday for computing time?

前端 未结 5 1852
闹比i
闹比i 2020-12-08 05:13

do you know how to use gettimeofday for measuring computing time? I can measure one time by this code:

  char buffer[30];
  struct timeval tv;

  time_t curt         


        
相关标签:
5条回答
  • 2020-12-08 05:25

    If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

    #include <time.h>
    
    int main()
    {
       clock_t start = clock();
       //... do work here
       clock_t end = clock();
       double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
       return 0;
    }
    

    hth

    0 讨论(0)
  • 2020-12-08 05:28

    No. gettimeofday should NEVER be used to measure time.

    This is causing bugs all over the place. Please don't add more bugs.

    0 讨论(0)
  • 2020-12-08 05:31

    Your curtime variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t values just fine.

    0 讨论(0)
  • 2020-12-08 05:34

    To subtract timevals:

    gettimeofday(&t0, 0);
    /* ... */
    gettimeofday(&t1, 0);
    long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
    

    This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

    long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;
    
    0 讨论(0)
  • 2020-12-08 05:36

    The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.


    Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

    The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.

    Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.

    <<

    0 讨论(0)
提交回复
热议问题