Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best, most accurate timer in C++?

Tags:

c++

timer

What is the best, most accurate timer in C++?

like image 728
Josh Morrison Avatar asked Apr 02 '11 04:04

Josh Morrison


People also ask

What Timer is the most accurate?

Atomic clocks are so accurate that they will lose one second approximately every 100 million years; for reference, the average quartz clock will lose one second every couple of years. On the other hand, Ye's optical lattice clock will lose one second every 15 billion years, making it the world's most accurate clock.

How accurate is clock () in C?

It has nanosecond precision.

Does C++ have a timer?

The timer() function in C++ returns the updated time as an object of the “time_t” type. The header file where this timer() function is defined is “ctime”. Here we will explain which type of functionalities a timer() can perform.


2 Answers

In C++11 you can portably get to the highest resolution timer with:

#include <iostream>
#include <chrono>
#include "chrono_io"

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    auto t1 = Clock::now();
    auto t2 = Clock::now();
    std::cout << t2-t1 << '\n';
}

Example output:

74 nanoseconds

"chrono_io" is an extension to ease I/O issues with these new types and is freely available here.

There is also an implementation of <chrono> available in boost (might still be on tip-of-trunk, not sure it has been released).

like image 193
Howard Hinnant Avatar answered Sep 23 '22 20:09

Howard Hinnant


The answer to this is platform-specific. The operating system is responsible for keeping track of timing and consequently, the C++ language itself provides no language constructs or built-in functions for doing this.

However, here are some resources for platform-dependent timers:

  • Windows API - SetTimer: http://msdn.microsoft.com/en-us/library/ms644906(v=vs.85).aspx
  • Unix - setitimer: http://linux.die.net/man/2/setitimer

A cross-platform solution might be boost::asio::deadline_timer.

like image 33
Nathan Osman Avatar answered Sep 23 '22 20:09

Nathan Osman