使用 C++ 和 Linux 的高分辨率计时器?
- 2024-10-11 08:36:00
- admin 原创
- 212
问题描述:
在 Windows 下,有一些方便的函数,例如QueryPerformanceCounter
frommmsystem.h
可以创建高分辨率计时器。Linux 上有类似的函数吗?
解决方案 1:
以前这里已经有人问过这个问题了——但基本上,有一个 boost ptime 函数可以使用,或者有一个 POSIX clock_gettime() 函数可以基本实现相同的用途。
解决方案 2:
对于 Linux (和 BSD),您需要使用clock_gettime()。
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
请参阅:此答案以获取更多信息
解决方案 3:
这里有一个链接,描述了如何在 Linux 和 Windows 上进行高分辨率计时...不,不要使用 RTSC。
解决方案 4:
对于 C++11,使用std::chrono::high_resolution_clock
。
例子:
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
}
输出:
Delta t2-t1: 131 nanoseconds
解决方案 5:
我只有这个链接:
http: //www.mjmwired.net/kernel/Documentation/rtc.txt
我很确定 RTC 就是你要找的。
编辑
其他答案似乎比我的更便携。
解决方案 6:
就我而言,没有比 Qt 的QTime类更易于使用的跨平台计时器。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD