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

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


<chrono> is the best. Visual Studio 2013 provides this feature. Personally, I have tried all the methods mentioned above. I strongly recommend you use the <chrono> library. It can track the wall time and at the same time have a good resolution (much less than a second).


The time_t structure is probably going to be an integer, which means it will have a resolution of second.

The first piece of code: It will only count the time that the CPU was doing something, so when you do sleep(), it will not count anything. It can be bypassed by counting the time you sleep(), but it will probably start to drift after a while.

The second piece: Only resolution of seconds, not so great if you need sub-second time readings.

For time readings with the best resolution you can get, you should do something like this:

double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}

double start_time = getUnixTime();
double stop_time, difference;

doYourStuff();

stop_time = getUnixTime();
difference = stop_time - start_time;

On most systems it's resolution will be down to few microseconds, but it can vary with different CPUs, and probably even major kernel versions.


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

Tags:

C++

Clock

Timing