2009-02-11 19 views
45

在Windows下也有像QueryPerformanceCountermmsystem.h一些方便的功能来创建一个高分辨率计时器。 Linux有没有类似的东西?使用C++和Linux的高分辨率定时器?

+0

http://stackoverflow.com/a/5524138/183120(跨平台C++ 11标准高分辨率计时器) – legends2k 2013-05-15 14:17:05

回答

31

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

+0

没” t知道Boost提供了定时器功能。谢谢:) – okoman 2009-02-11 20:33:24

+1

或从[ACE](HTTP使用[HighResTimer(http://www.dre.vanderbilt.edu/Doxygen/Stable/ace/classACE__High__Res__Timer.html)://www.cs.wustl。 edu /〜schmidt/ACE.html)库。 – lothar 2009-04-12 02:00:32

29

对于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了解更多信息

1

对于我的钱,还有比Qt的QTime类不容易使用的跨平台的定时器。

2

用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