Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High resolution timer with C++ and Linux?

Tags:

c++

linux

timer

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

like image 990
okoman Avatar asked Feb 11 '09 20:02

okoman


People also ask

What is high resolution timer in Linux?

The High Resolution Timers system allows a user space program to be wake up from a timer event with better accuracy, when using the POSIX timer APIs. Without this system, the best accuracy that can be obtained for timer events is 1 jiffy. This depends on the setting of HZ in the kernel.

What is Hrtime Linux?

This patch introduces a new subsystem for high-resolution kernel timers. One might ask the question: we already have a timer subsystem (kernel/timers.

What is Ktime_t?

There is a new type, ktime_t, which is used to store a time value in nanoseconds. This type, found in <linux/ktime. h>, is meant to be used as an opaque structure. And, interestingly, its definition changes depending on the underlying architecture.


2 Answers

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.

like image 74
Nik Reiman Avatar answered Oct 09 '22 22:10

Nik Reiman


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

like image 36
grieve Avatar answered Oct 09 '22 21:10

grieve