Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing algorithm: clock() vs time() in C++

Tags:

c++

timing

clock

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?

like image 692
blaze Avatar asked Sep 01 '12 20:09

blaze


People also ask

Is clock () in C accurate?

It has nanosecond precision.

How does clock () work in C?

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 );

What is clock in C program?

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.

How do you use a clock function?

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 .


2 Answers

<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.

like image 119
Rapptz Avatar answered Oct 05 '22 18:10

Rapptz


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

like image 22
David Grayson Avatar answered Oct 05 '22 18:10

David Grayson