如何在C++中获取时间,最好是多平台
How to get TIME in C++, preferably multi platform
我一直在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
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 在编译时间之前抓取常数值
- 在 c++(多平台)中获得可靠的单调时间
- 测量Windows平台上本机C++的运行时间(秒)
- 是否有一个平台不将 std::time_t 表示为 unix 时间
- C、 所有平台中进程的C++CPU使用率和内存使用率+当前时间的可用网络下行链路带宽
- 如何在C++中获取时间,最好是多平台
- c++使运行时间独立于平台
- Linux LibdvbV5 EIT抓取-没有得到足够的时间