如何在C++中获取时间,最好是多平台

How to get TIME in C++, preferably multi platform

本文关键字:平台 取时间 C++ 获取      更新时间:2023-10-16

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

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

谢谢!

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

Precision是一个实现细节,例如,它应该在Windows上实现为QueryPerformanceCounter

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

如果您想要跨平台兼容性,ctime中的clock()函数(请参阅文档)可能是您的最佳选择。它在Visual Studio中以毫秒为单位(尽管这不能保证它实际上以1毫秒为增量),在其他编译器中可能类似。

每个平台都有自己的方式来获得更高分辨率的时间。在Windows上有timeGetTime()QueryPerformanceCounter()。你可以在线阅读有关它们的信息;每一篇都有很多文章(这里有一篇)。如果你关心其他平台,你必须四处搜索或查阅他们的文档,以获得他们自己的高分辨率计时功能。

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