首页 > 解决方案 > 如果我对循环进行以下更改,执行时间会减少吗?

问题描述

假设我想为一个大数 ( 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 会提供更好的执行时间吗?

标签: c++c

解决方案


我必须使用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.

所以,似乎第一个场景有更好的执行时间......

注意:数量较少时没有区别,最好使用一个循环而不是两个循环。


推荐阅读