0

我一直在使用Windows 中的GetTickCount(),但我读到它的性能/分辨率很差,我想问一下什么是获得时间的最佳方法。

我尝试使用<ctime>库,但它不会持续毫秒或微秒,我需要达到那个精度的东西。

谢谢!

4

3 回答 3

7

如果使用 C++11,您可以使用std::chrono::high_resolution_clock

精度是一个实现细节,例如它应该QueryPerformanceCounter在 Windows 上实现。

#include <chrono>
#include <iostream>

int main(int argc, char *argv[])
{
   auto t1 = std::chrono::high_resolution_clock::now();
   auto t2 = std::chrono::high_resolution_clock::now();
   std::cout << "It took " << std::chrono::nanoseconds(t2 - t1).count() << " nanoseconds" << std::endl;

   return 0;
}
于 2013-07-20T20:16:43.600 回答
1

如果您想要跨平台兼容性,那么(请参阅docsclock() )中的功能可能是您最好的选择。它在 Visual Studio 中以毫秒为单位(尽管不能保证它实际上以 1 毫秒的增量前进),并且在其他编译器中可能类似。ctime

每个平台都有自己的方式来获得更高分辨率的时序。在 Windows 上有timeGetTime()QueryPerformanceCounter()。您可以在线阅读它们;每个都有大量文章(这里有一篇)。如果还有其他您关心的平台,您将不得不四处搜索或查阅他们的文档以了解他们自己的高分辨率计时功能。

于 2013-07-20T19:56:26.143 回答
0

看看这个,它的性能似乎更好 http://www.boost.org/doc/libs/1_38_0/doc/html/date_time.html

于 2013-07-20T22:23:00.027 回答