The time command returns the time elapsed in execution of a command.

If I put a "gettimeofday()" at the start of the command call (using system() ), and one at the end of the call, and take a difference, it doesn't come out the same. (its not a very small difference either)

Can anybody explain what is the exact difference between the two usages and which is the best way to time the execution of a call?

Thanks.

有帮助吗?

解决方案

The Unix time command measures the whole program execution time, including the time it takes for the system to load your binary and all its libraries, and the time it takes to clean up everything once your program is finished.

On the other hand, gettimeofday can only work inside your program, that is after it has finished loading (for the initial measurement), and before it is cleaned up (for the final measurement).

Which one is best? Depends on what you want to measure... ;)

其他提示

time() returns time since epoch in seconds.

gettimeofday(): returns:

struct timeval {
       time_t      tv_sec;     /* seconds */
       suseconds_t tv_usec;    /* microseconds */
};

It's all dependent on what you are timing. If you are trying to time something in seconds, then time() is probably your best bet. If you need higher resolution than that, then I would consider gettimeofday(), which gives up to microsecond resolution (1 / 1000000th of a second).

If you need even higher resolution than that, consider using clock() and CLOCKS_PER_SECOND, just note that clock() is rarely an accurate description for the amount of time taken, but rather the number of CPU cycles used.

Each time function has different precision. In C++11 you would use std::chrono:

using namespace std::chrono;

auto start = high_resolution_clock::now();
/* do stuff*/
auto end = high_resolution_clock::now();

float elapsedSeconds = duration_cast<duration<float>>(end-start).count();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top