如何在C++中获得TIME,最好是多平台

Dan*_*cco 0 c++

我一直在使用Windows的GetTickCount(),但我读过它的性能/分辨率很差,我想问一下最好的方法是什么.

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

谢谢!

Cas*_*yer 7

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

Precision是一个实现细节,例如它应该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;
}
Run Code Online (Sandbox Code Playgroud)