High resolution timer with C++ and Linux?

情到浓时终转凉″ 提交于 2019-12-17 02:23:39

问题


Under Windows there are some handy functions like QueryPerformanceCounter from mmsystem.h to create a high resolution timer. Is there something similar for Linux?


回答1:


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.




回答2:


For Linux (and BSD) you want to use 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 answer for more information




回答3:


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

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




回答4:


With C++11, use 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



回答5:


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

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

EDIT

Other answers seem more portable than mine.




回答6:


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



来源:https://stackoverflow.com/questions/538609/high-resolution-timer-with-c-and-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!