For timing an algorithm (approximately in ms), which of these two approaches is better:
clock_t start = clock(); algorithm(); clock_t end = clock(); double time = (double) (end-start) / CLOCKS_PER_SEC * 1000.0;
Or,
time_t start = time(0); algorithm(); time_t end = time(0); double time = difftime(end, start) * 1000.0;
Also, from some discussion in the C++ channel at Freenode, I know clock has a very bad resolution, so the timing will be zero for a (relatively) fast algorithm. But, which has better resolution time() or clock()? Or is it the same?
It has nanosecond precision.
clock() function in C/C++ The clock() function returns the approximate processor time that is consumed by the program. The clock() time depends upon how the operating system allocate resources to the process that's why clock() time may be slower or faster than the actual clock. Syntax: clock_t clock( void );
C library function - clock() The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.
To measure the time spent in a program, call the clock() function at the start of the program, and subtract its returned value from the value returned by subsequent calls to clock(). Then, to obtain the time in seconds, divide the value returned by clock() by CLOCKS_PER_SEC .
<chrono>
would be a better library if you're using C++11.
#include <iostream> #include <chrono> #include <thread> void f() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { auto t1 = std::chrono::high_resolution_clock::now(); f(); auto t2 = std::chrono::high_resolution_clock::now(); std::cout << "f() took " << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << " milliseconds\n"; }
Example taken from here.
It depends what you want: time
measures the real time while clock
measures the processing time taken by the current process. If your process sleeps for any appreciable amount of time, or the system is busy with other processes, the two will be very different.
http://en.cppreference.com/w/cpp/chrono/c/clock
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With