gpt4 book ai didi

c++ - 使用 high_resolution_clock 分析 C++ 程序

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:15 26 4
gpt4 key购买 nike

我想分析我的 C++ 程序,并使用了 high_resolution_clock为了这个目的。作为示例提供了该问题的示例代码。我尝试了三种不同的方法。

示例 1

#include<iostream>
#include <chrono>

using namespace std;
using namespace chrono;

unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
while(i < 10000000){
high_resolution_clock::time_point t1 = high_resolution_clock::now();
j += i;
i++;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
}
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}

example在循环内使用时钟并且运行良好,给出预期的结果。

示例 2

#include<iostream>
#include <chrono>

using namespace std;
using namespace chrono;

unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
while(i < 10000000){
j += i;
i++;
}
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}

example显示 0 时间,我对此表示怀疑。

示例 3

#include<iostream>
#include <chrono>

using namespace std;
using namespace chrono;

unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
while(i < 10000000){
j += i;
i++;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
}
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}

example显示 3792420263 微秒,我也对此表示怀疑。

示例 2示例 3 中的问题是什么。三者中哪一个是正确的。

最佳答案

示例 2 由编译器优化,因此如果您想查看循环运行时间,您应该禁用任何编译器优化。

示例 3 没有任何意义,因为您在每个循环中都添加了时间差,而结果是数字,没有说明循环运行时间。此外,您在使用 32 位 unsigned int ttime 的循环中遇到许多溢出。

因此,分析真实代码的最佳解决方案是示例 2。不要担心你的零输出,如果你在 t1t2 创建之间添加任何“合理的代码”,你会得到更好的数字。

关于c++ - 使用 high_resolution_clock 分析 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45606039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com