使用 C++ 和 Linux 的高分辨率计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/538609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:59:15  来源:igfitidea点击:

High resolution timer with C++ and Linux?

c++linuxtimer

提问by okoman

Under Windows there are some handy functions like QueryPerformanceCounterfrom mmsystem.hto create a high resolution timer. Is there something similar for Linux?

在Windows下也有像一些方便的功能,QueryPerformanceCountermmsystem.h创建高分辨率定时器。Linux 有类似的东西吗?

采纳答案by Nik Reiman

It's been asked before here-- but basically, there is a boost ptime function you can use, or a POSIX clock_gettime() function which can serve basically the same purpose.

之前有人问过这里- 但基本上,你可以使用一个 boost ptime 函数,或者一个 POSIX clock_gettime() 函数,它可以用于基本相同的目的。

回答by Oliver N.

I have nothing but this link: http://www.mjmwired.net/kernel/Documentation/rtc.txt

我只有这个链接:http: //www.mjmwired.net/kernel/Documentation/rtc.txt

I'm pretty sure RTC is what you are looking for though.

我很确定 RTC 是您正在寻找的。

EDIT

编辑

Other answers seem more portable than mine.

其他答案似乎比我的更便携。

回答by grieve

For Linux (and BSD) you want to use clock_gettime().

对于 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
}

See: This answerfor more information

请参阅:此答案以获取更多信息

回答by tjd

Here's a link describing how to do high-resolution timing on Linux and Windows... and no, Don't use RTSC.

这是一个描述如何在 Linux 和 Windows 上进行高分辨率计时的链接……不,不要使用 RTSC。

https://web.archive.org/web/20160330004242/http://tdistler.com/2010/06/27/high-performance-timing-on-linux-windows

https://web.archive.org/web/20160330004242/http://tdistler.com/2010/06/27/high-performance-timing-on-linux-windows

回答by Alan Turing

For my money, there is no easier-to-use cross-platform timer than Qt's QTimeclass.

就我而言,没有比 Qt 的QTime类更易于使用的跨平台计时器了。

回答by Martin G

With C++11, use std::chrono::high_resolution_clock.

对于 C++11,使用std::chrono::high_resolution_clock.

Example:

例子:

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

Output:

输出:

Delta t2-t1: 131 nanoseconds