开始一个for循环需要多长时间

How long does it take a for loop to get started?

本文关键字:循环 长时间 for 一个 开始      更新时间:2023-10-16

我正在用c++编写代码,其中我可以选择运行1个for循环,其中包含4个加法操作,或者运行4个单独的for循环,每个循环包含1个加法操作。(作为旁注,我正在考虑这一点,因为4-循环1-加法将意味着我在我正在编写的程序中分配1/4的内存)

我本能地期望1-loop-4-addition更快,我做了一个快速基准测试来证明这一点。1-循环-4-加法的时间大约是4-循环-1-加法的一半

我的问题是:是什么过程造成了这种差异?

下面是我用于测试的代码——我是数学家而不是程序员,所以我很有可能会做一些愚蠢的事情。我用的是二维数组因为这就是我要编码的。

#include <stdio.h>
#include <ctime>
#include <iostream>
using namespace std;
int main(){
    int Nx=100;
    int Ny=Nx;
    double holder=0;
    double test[Nx][Ny];
    double test1[Nx][Ny];
    double test2[Nx][Ny];
    double test3[Nx][Ny];
    double test4[Nx][Ny];
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Nx;j++){
            test[i][j]=1;
            test1[i][j]=1;
            test2[i][j]=1;
            test3[i][j]=1;
            test4[i][j]=1;
        }
    }
    clock_t begin= clock();
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Ny;j++){
            holder=holder + test[i][j];
        }
    }
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Ny;j++){
            holder=holder + test[i][j];
        }
    }
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Ny;j++){
            holder=holder + test[i][j];
        }
    }
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Ny;j++){
            holder=holder + test[i][j];
        }
    }
    clock_t end = clock();
    double elapsed = (double) (end-begin)/CLOCKS_PER_SEC;
    cout<<"Time to run 1 addition in 4 for loops="<<elapsed<<endl;
    begin= clock();
    for(int i=0;i<Nx;i++){
        for(int j=0;j<Ny;j++){
            holder=holder + test1[i][j]+ test2[i][j]+ test3[i][j]+ test4[i][j];
        }
    }
    end = clock();
    elapsed = (double) (end-begin)/CLOCKS_PER_SEC;
    cout<<"Time to run 4 additions in 1 for loop="<<elapsed<<endl;
}

对于第一个选项,您执行4*(NxNy)操作,而对于第二个选项,您执行NxNy操作,因此对于较大的Nx,Ny

,第二个循环完成得更快是正常的。

让我们仔细看看这两个循环,看看发生了什么事情。如果仔细观察,2D数组的addition操作次数是相同的。但两种方法比较i<Nxj<Ny的次数以及ij的增量不同。在1st方法中它是4倍多。

这可能是两个方法执行时间不同的原因之一。