Under Windows there are some handy functions like QueryPerformanceCounter
from mmsystem.h
to create a high resolution timer.
Is there something similar for Linux?
Asked
Active
Viewed 8.0k times
46
![](../../users/profiles/35903.webp)
okoman
- 5,279
- 9
- 37
- 44
-
http://stackoverflow.com/a/5524138/183120 (Cross-platform C++11 standard high resolution timer) – legends2k May 15 '13 at 14:17
6 Answers
31
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.
![](../../users/profiles/-1.webp)
Community
- 1
- 1
![](../../users/profiles/14302.webp)
Nik Reiman
- 36,184
- 26
- 100
- 159
-
-
1Or use the [HighResTimer](http://www.dre.vanderbilt.edu/Doxygen/Stable/ace/classACE__High__Res__Timer.html) from the [ACE](http://www.cs.wustl.edu/~schmidt/ACE.html) library. – lothar Apr 12 '09 at 02:00
-
3@lothar: +1 for pointer to ACE library, thanks. The link you gave was stale, here's a new one: http://www.dre.vanderbilt.edu/Doxygen/Stable/libace-doc/a00227.html – BD at Rivenhill May 16 '11 at 16:02
30
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
-
8Of course, you need to be aware of the difference between `CLOCK_MONOTONIC` and `CLOCK_REALTIME` - the former has its zero-point set to something arbitrary at system boot, and as such is only useful for relative comparisons between two `CLOCK_MONOTONIC` measurements (but is unaffected by wallclock adjustments) – bdonlan Jan 21 '11 at 17:57
8
Here's a link describing how to do high-resolution timing on Linux and Windows... and no, Don't use RTSC.
![](../../users/profiles/4587527.webp)
Somesh Kumar
- 5,730
- 4
- 28
- 44
![](../../users/profiles/228408.webp)
tjd
- 467
- 8
- 14
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
![](../../users/profiles/3545094.webp)
Martin G
- 14,280
- 9
- 69
- 82
1
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.
![](../../users/profiles/39122.webp)
Oliver N.
- 2,458
- 19
- 20
1
For my money, there is no easier-to-use cross-platform timer than Qt's QTime class.
![](../../users/profiles/627517.webp)
Alan Turing
- 11,403
- 14
- 66
- 114