c++ - 如果我对循环进行以下更改,执行时间会减少吗?
问题描述
假设我想为一个大数 ( N>10^4
) 运行一个循环。
场景一:
for (i=1; i<=N; i++) {
if(num%i==0)
count++;
}
场景二:
for(i=1; i<N; i=i+2)
{
if(num%i==0)
count++;
}
for(i=2;i<N;i=i+2)
{
if(num%i==0)
count++;
}
方案 2 会提供更好的执行时间吗?
解决方案
我必须使用chrono
标准库对其进行测试,以获得每个场景的经过时间:
假设N
是:
#define N 3000000000
第一种情况:
void scenario1()
{
int count = 0;
int num = 10;
for (int i=1; i<=N; i++) {
if(num%i==0)
count++;
}
}
第二个场景:
void scenario2()
{
int count = 0;
int num = 10;
for(int i=1; i<N; i=i+2)
{
if(num%i==0)
count++;
}
for(int i=2;i<N;i=i+2)
{
if(num%i==0)
count++;
}
}
在主要:
int main()
{
// Record start time
auto start = std::chrono::high_resolution_clock::now();
// Portion of code to be timed
scenario1();
// Record end time
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
cout << "Elapsed time for the 1st scenario is : " << elapsed.count() << " second." << endl;
start = std::chrono::high_resolution_clock::now();
// Portion of code to be timed
scenario2();
// Record end time
finish = std::chrono::high_resolution_clock::now();
elapsed = finish - start;
cout << "Elapsed time for the 2st scenario is : " << elapsed.count() << " second." << endl;
return 0;
}
输出是:
Elapsed time for the 1st scenario is : 13.842 second.
Elapsed time for the 2st scenario is : 14.3887 second.
所以,似乎第一个场景有更好的执行时间......
注意:数量较少时没有区别,最好使用一个循环而不是两个循环。
推荐阅读
- elasticsearch - 如何恢复弹性搜索中被 PUT 请求覆盖的索引模板的先前值?
- osgi - 是否有任何其他配置可以从 maven-bundle-plugin 版本 2.5.3 迁移到 3.2.0
- python - 如何在pyvips中分配图像组件?
- android - 每次更新视图时,Android 垂直滚动视图会自动移动到顶部
- python - 评估 Sympy 函数
- wordpress - 在 Woocommerce Shop Loop 之后显示 ACF 自定义块
- apache - 使用 .htaccess 从 URL 中删除查询字符串
- python - 从不同 python 文件中的函数导入 2 个数据帧
- javascript - 在画布上用鼠标绘制矩形与鼠标坐标不同步
- string - 在 Rust 中查询结构向量