首页 > 解决方案 > Know if CPU supports nanoseconds

问题描述

I am trying to get elapsed time in nanoseconds using C++ in visual studio. I did some testing and the measures always end with 00. Does it mean that my processor (Ryzen 7-1800X) doesn't support ~1 nanosecond resolution but only ~100ns? Can I enable it somehow?

auto start = std::chrono::high_resolution_clock::now();    
for (int i = 0; i < 10; i++) {
    //stuff
    auto elapsed = std::chrono::high_resolution_clock::now() - start;
    long long nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count();
    std::cout << "\n" << nanoseconds << "\n";
}

标签: c++windowsperformancetimecpu

解决方案


In MSVC 2015+ std::chrono::high_resolution_clock is based on QueryPerformanceCounter, which has a 100ns resolution.

On Windows, QueryPerformanceCounter is the fastest userland timer. If you want an even higher resolution, you can try the RDTSC instruction (__rdtsc) which returns the CPU cycle counter. But it's a very tricky one to use properly and is not recommended.

It seems on Windows you're pretty much stuck to a 100ns resolution. Keep in mind that in Windows world 100ns is a very short time - it equals roughly 300 instructions. Just one call to QueryPerformanceCounter already takes around 1000 instructions.


推荐阅读