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

戏子无情 提交于 2019-11-29 19:25:23

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

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

How about gettimeofday? When it is called it updates two structs, with timing information. Usually, the left hand struct is enough, which will carry time since the Epoch, 01-01-1970 00:00:00 (UTC). It can be used as follows:

#include <time.h>

struct timeval start;
double mtime, seconds, useconds;
gettimeofday(&start, NULL); //left hand struct is usually enough
seconds  = start.tv_sec; //time in seconds
useconds = start.tv_usec; //time in microseconds
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!