代码之家  ›  专栏  ›  技术社区  ›  okoman

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

  •  46
  • okoman  · 技术社区  · 17 年前

    在Windows下,有一些方便的功能,如 QueryPerformanceCounter mmsystem.h

    6 回复  |  直到 17 年前
        1
  •  31
  •   Community Mohan Dere    9 年前

    一直都是 asked before here --但基本上,有一个boost optime函数可以使用,或者一个POSIX clock_gettime()函数可以用于基本相同的目的。

        2
  •  30
  •   Community Mohan Dere    9 年前

    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

        3
  •  8
  •   Somesh Kumar tjd    8 年前

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

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

        4
  •  4
  •   Martin G    9 年前

    对于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
  •  1
  •   Oliver N.    17 年前

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

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

        6
  •  1
  •   Alan Turing    14 年前

    在我看来,没有什么比Qt更容易使用跨平台计时器了 QTime