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

2019-01-19 00:46发布

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

标签: c++ timer
4条回答
唯我独甜
2楼-- · 2019-01-19 00:53

Under windows it would be QueryPerformanceCounter, though seeing as you didn't specify any conditions it possible to have an external ultra high resolution timer that has a c++ interface for the driver

查看更多
对你真心纯属浪费
3楼-- · 2019-01-19 01:00

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).

查看更多
Luminary・发光体
4楼-- · 2019-01-19 01:03

The C++ standard doesn't say a whole lot about time. There are a few features inherited from C via the <ctime> header.

The function clock is the only way to get sub-second precision, but precision may be as low as one second (it is defined by the macro CLOCKS_PER_SEC). Also, it does not measure real time at all, but processor time.

The function time measures real time, but (usually) only to the nearest second.

To measure real time with subsecond precision, you need a nonstandard library.

查看更多
神经病院院长
5楼-- · 2019-01-19 01:12

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:

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

查看更多
登录 后发表回答