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中文網其他相關文章!