假设我想运行一个循环(N>10^4
)。
方案1:
for (i=1; i<=N; i++) {
if(num%i==0)
count++;
}
方案2:
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会缩短执行时间吗?
答案 0 :(得分: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.
因此,第一种情况似乎具有更好的执行时间...
注意: :以较小的数字没有区别,最好使用一个循环而不是两个循环。