問題描述
我對在 Windows 中使用 C++ 測量精確到納秒的特定時間點很感興趣.這可能嗎?如果不是,是否可以至少以微秒為單位獲得特定時間?任何庫都應該這樣做,除非我認為托管代碼是可能的.謝謝
I'm interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code. thanks
推薦答案
如果您有一個線程應用程序在多核計算機上運行 QueryPerformanceCounter
可以(并將)根據代碼的內核返回不同的值正在執行.請參閱這篇 MSDN 文章.(rdtsc
也有同樣的問題)
If you have a threaded application running on a multicore computer QueryPerformanceCounter
can (and will) return different values depending on which core the code is executing on. See this MSDN article. (rdtsc
has the same problem)
這不僅僅是一個理論問題;我們在我們的應用程序中遇到了它,并且不得不得出結論,唯一可靠的時間源是 timeGetTime
,它只有 ms 精度(幸運的是,在我們的例子中已經足夠了).我們還嘗試為我們的線程固定線程關聯,以保證每個線程始終從 QueryPerformanceCounter
獲得一致的值,這有效,但它絕對降低了應用程序的性能.
This is not just a theoretical problem; we ran into it with our application and had to conclude that the only reliable time source is timeGetTime
which only has ms precision (which fortunately was sufficient in our case). We also tried fixating the thread affinity for our threads to guarantee that each thread always got a consistent value from QueryPerformanceCounter
, this worked but it absolutely killed the performance in the application.
總而言之,Windows 上沒有一個可靠計時器可以用于以微秒精度計時(至少在多核計算機上運行時不會).
To sum things up there isn't a reliable timer on windows that can be used to time thing with micro second precision (at least not when running on a multicore computer).
這篇關于Windows中的C++高精度時間測量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!