Easily measure elapsed time

前端 未结 26 2186
栀梦
栀梦 2020-11-22 04:13

I am trying to use time() to measure various points of my program.

What I don\'t understand is why the values in the before and after are the same? I understand thi

26条回答
  •  逝去的感伤
    2020-11-22 05:03

    From what is see, tv_sec stores the seconds elapsed while tv_usec stored the microseconds elapsed separately. And they aren't the conversions of each other. Hence, they must be changed to proper unit and added to get the total time elapsed.

    struct timeval startTV, endTV;
    
    gettimeofday(&startTV, NULL); 
    
    doSomething();
    doSomethingLong();
    
    gettimeofday(&endTV, NULL); 
    
    printf("**time taken in microseconds = %ld\n",
        (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
        );
    

提交回复
热议问题