c++ - 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";
}
解决方案
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.
推荐阅读
- javascript - onClick 检测 li 和嵌套在 li 中的按钮
- python - 如何创建用于更改数据框名称的循环
- javascript - 根据 Javascript 中现有对象数组的值创建一个数组
- ios - 从另一个类 Swift 更新视图控制器的 UI
- arm - 使用 stm32 发送一条短信后 sim808 冻结
- java - 从 HashMap 获取以添加到 ArrayList 是否通过引用将其存储在 ArrayList 中?
- javascript - 在 JavaScript 中将所有键合并到具有相同 ID 的单个对象中
- flutter - 如何使用 Dart 从 Webview 中按类名获取图像 url
- firebase - 通过 Firebase Functions 将图像下载到用户本地计算机
- gmail - 如何过滤来自以下地址的垃圾邮件:“from@<
>.com”?