c++ - std::chrono 重复调用 QueryPerformanceFrequency?

标签 c++ time std clock c++-chrono

每当我打电话时:

std::chrono::high_resolution_clock::now().time_since_epoch().count();

它的组装说明是:

std::chrono::high_resolution_clock::now().time_since_epoch().count();
00007FF7D9E11840  call        qword ptr [__imp__Query_perf_frequency (07FF7D9E14090h)]  
00007FF7D9E11846  call        qword ptr [__imp__Query_perf_counter (07FF7D9E140A0h)] 

我以前用过 Windows API 时钟,我认为正确的方法是查询一次频率。

在 Microsoft 文档中它说:

QueryPerformanceFrequency Retrieves the frequency of the performance counter. The frequency of the performance counter is fixed at system boot and is consistent across all processors. Therefore, the frequency need only be queried upon application initialization, and the result can be cached.

这是一个循环,所以我认为对 QueryPerformanceFrequency 的调用是重复完成的。这是在 Release模式和/O2 优化下构建的。

此外,如果我在 Debug模式下构建,它会生成以下程序集:

std::chrono::high_resolution_clock::now().time_since_epoch().count();
00007FF774FC9D19  lea         rcx,[rbp+398h]  
00007FF774FC9D20  call        std::chrono::steady_clock::now (07FF774FB1226h)  
00007FF774FC9D25  lea         rdx,[rbp+3B8h]  
00007FF774FC9D2C  mov         rcx,rax  
00007FF774FC9D2F  call        std::chrono::time_point<std::chrono::steady_clock,std::chrono::duration<__int64,std::ratio<1,1000000000> > >::time_since_epoch (07FF774FB143Dh)  
00007FF774FC9D34  mov         rcx,rax  
00007FF774FC9D37  call        std::chrono::duration<__int64,std::ratio<1,1000000000> >::count (07FF774FB1361h) 

我不懂汇编,也不知道为什么在Release模式下有调用Windows API而在Debug模式下没有提及。另外,我正在使用 Visual Studio。

谢谢。

最佳答案

VS 的优化器似乎没有将 QueryPerformanceFrequency 的调用放在循环之外。它没有意识到在第一次迭代之后的每次迭代中输出总是相同的,因此它无法对其进行优化,而任何理智的优化器都会这样做:)

可能是缺失的功能或其他东西,而不是我认为的错误,因为我会说 VS 在循环之外优化了对 foo 的调用(我无法访问 VS片刻,所以我无法测试):

int value = 0;
void foo() { value = 2; }

for (int i = 0; i < 10; ++i) {
    foo();
    std::cout << i * value << '\n';
}

之所以没有调用QueryPerformance* 函数是因为在Debug 中,不允许优化器进行优化。优化器发现对 native Windows API 的调用比对标准库实现的调用更快,因此它替换了相应的调用。

关于c++ - std::chrono 重复调用 QueryPerformanceFrequency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347313/

相关文章:

c++ - Windows时区写入注册表是否可靠?

sql - FORMAT([Time], 'hh:mm' ) 返回 NULL

c++ - 在没有 boost::counting_iterator 的情况下插入一系列连续整数的最佳方法

c++ - std::function 回调与观察者模式中的参数(注册主题上的占位符)

c++ - 二维矩阵 STATUS_ACCESS_VIOLATION 错误

c++ - 减去无符号整数的有符号结果?

c++ - 重新声明枚举器

c++ - 在重载的 operator new 中初始化类成员是否未定义?

linux - 内核空间和用户空间中的时间差异

c++ - 我需要关闭 std::fstream 吗?