时序algorithm:C ++中的clock()与time()

为了计算algorithm(大约以毫秒为单位),这两种方法中的哪一种更好:

clock_t start = clock(); algorithm(); clock_t end = clock(); double time = (double) (end-start) / CLOCKS_PER_SEC * 1000.0; 

要么,

 time_t start = time(0); algorithm(); time_t end = time(0); double time = difftime(end, start) * 1000.0; 

另外,从Freenode的C ++频道的一些讨论中,我知道时钟的分辨率非常差,所以对于(相对)快的algorithm,时序将为零。 但是,有更好的parsing时间()或时钟()? 还是一样?

这取决于你想要的: time测量实时,而clock测量当前进程所花费的处理时间。 如果你的进程hibernate了相当长的时间,或者系统忙于其他进程,那么两者将会有很大的不同。

http://en.cppreference.com/w/cpp/chrono/c/clock

如果你使用C ++ 11,那么<chrono>会是一个更好的库。

 #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"; } 

取自这里的例子。

time_t结构可能会是一个整数,这意味着它将有一个秒的决议。

第一块代码:它只会计算CPU做某事的时间,所以当你做sleep()时,它不会计算任何东西。 它可以通过计算你的睡眠时间()来绕开,但它可能会在一段时间后开始漂移。

第二件:只有秒的分辨率,如果你需要亚秒的时间读数,不是那么好。

对于你能得到的最佳分辨率的时间读数,你应该这样做:

 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; 

在大多数系统中,分辨率会降至几微秒,但是可能因不同的CPU而不同,甚至可能是主要的内核版本。

<chrono>是最好的。 Visual Studio 2013提供了这个function。 就个人而言,我已经尝试了上面提到的所有方法。 我强烈build议你使用<chrono>库。 它可以跟踪墙的时间,同时具有很好的分辨率(远低于一秒)。

gettimeofday怎么样? 当它被称为它更新两个结构,与时间信息。 通常情况下,左边的结构已经足够了,从时代01-01-1970 00:00:00(UTC)开始,这个结构会运行。 它可以使用如下:

 #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