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

blaze picture blaze · Sep 1, 2012 · Viewed 90.9k times · Source

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?

Answer

Rapptz picture Rapptz · Sep 1, 2012

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