【问题标题】:High resolution timer with C++ and Linux?使用 C++ 和 Linux 的高分辨率计时器?
【发布时间】:2009-02-11 20:24:54
【问题描述】:

在 Windows 下,有一些方便的函数,如 mmsystem.h 中的 QueryPerformanceCounter 来创建高分辨率计时器。 Linux 有类似的东西吗?

【问题讨论】:

标签: c++ linux timer


【解决方案1】:

一直是asked before here——但基本上,你可以使用一个 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
}

请参阅:This answer 了解更多信息

【讨论】:

  • 当然,您需要注意CLOCK_MONOTONICCLOCK_REALTIME 之间的区别 - 前者在系统启动时将其零点设置为任意值,因此仅对两个CLOCK_MONOTONIC 测量值之间的相对比较(但不受挂钟调整的影响)
【解决方案3】:

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

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

【讨论】:

    【解决方案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 类更易于使用的跨平台计时器了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-02
          • 2011-04-02
          • 1970-01-01
          • 1970-01-01
          • 2011-10-31
          相关资源
          最近更新 更多