C 语言的跨平台高分辨率定时器
用 C 语言实现一个简单的定时器机制,可在 Windows 和 Linux 上运行,精度为毫秒是一项常见任务。为了解决这个问题,C 11 引入了
使用
#include <iostream> #include <chrono> #include "chrono_io" // For ease of I/O int main() { typedef std::chrono::high_resolution_clock Clock; auto t1 = Clock::now(); auto t2 = Clock::now(); std::cout << t2 - t1 << '\n'; }
通过解决方法提高精度:
但是,如果您在后续调用中遇到高延迟std::chrono::high_resolution_clock(如在 VS11 上观察到的),存在一种解决方法,它利用内联汇编并硬连线机器的时钟速度。
自定义
#include <chrono> struct clock { typedef unsigned long long rep; typedef std::ratio<1, 2800000000> period; // Machine-specific clock speed typedef std::chrono::duration<rep, period> duration; typedef std::chrono::time_point<clock> time_point; static const bool is_steady = true; static time_point now() noexcept { unsigned lo, hi; asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); return time_point(duration(static_cast<rep>(hi) << 32 | lo)); } static bool check_invariants() { static_assert(1 == period::num, "period must be 1/freq"); static_assert(std::is_same<rep, duration::rep>::value, "rep and duration::rep must be the same type"); static_assert(std::is_same<period, duration::period>::value, "period and duration::period must be the same type"); static_assert(std::is_same<duration, time_point::duration>::value, "duration and time_point::duration must be the same type"); return true; } static const bool invariants = check_invariants(); };
使用自定义:
using std::chrono::nanoseconds; using std::chrono::duration_cast; auto t0 = clock::now(); auto t1 = clock::now(); nanoseconds ns = duration_cast<nanoseconds>(t1 - t0);
以上是如何用C语言实现跨平台高分辨率定时器?的详细内容。更多信息请关注PHP中文网其他相关文章!