How to get the running of time of my program with gettimeofday()
So I get the time at the beginning of the code, run it开发者_C百科, and then get the time.
struct timeval begin, end;
gettimeofday(&begin, NULL);
//code to time
gettimeofday(&end, NULL);
//get the total number of ms that the code took:
unsigned int t = end.tv_usec - begin.tv_usec;
Now I want to print it out in the form "**code took 0.007 seconds to run" or something similar.
So two problems:
1) t seems to contain a value of the order 6000, and I KNOW the code didn't take 6 seconds to run.
2) How can I convert t to a double, given that it's an unsigned int? Or is there an easier way to print the output the way I wanted to?
timeval
contains two fields, the seconds part and the microseconds part.
tv_usec
(u meaning the greek letter mu, which stands for micro) is the microseconds. Thus when you get 6000, that's 6000 microseconds elapsed.
tv_sec
contains the seconds part.
To get the value you want as a double use this code:
double elapsed = (end.tv_sec - begin.tv_sec) +
((end.tv_usec - begin.tv_usec)/1000000.0);
Make sure you include the tv_sec
part in your calculations. gettimeofday
returns the current time, so when the seconds increments the microsecond will go back to 0, if this happens while your code is running and you don't use tv_sec
in your calculation, you will get a negative number.
1) That's because usec
is not 6000 milliseconds, it's 6000 microseconds (6 milliseconds or 6 one-thousandths of a second).
2) Try this: (double)t / 1000000
That will convert t to a double, and then divide it by one million to find the number of seconds instead of the number of microseconds.
精彩评论