C - gettimeofday for computing time?

前端 未结 5 1871
闹比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: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;
    

提交回复
热议问题