开始一个for循环需要多长时间
How long does it take a for loop to get started?
我正在用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<Nx
和j<Ny
的次数以及i
和j
的增量不同。在1st
方法中它是4倍多。
这可能是两个方法执行时间不同的原因之一。
相关文章:
- while循环中while循环的时间复杂度是多少
- 使用Boost Interprocess创建托管共享内存需要很长时间
- SFML RenderWindow打开窗口需要很长时间
- 具有嵌套 if-else 的循环的时间复杂度
- Kafka C++客户端需要很长时间才能收到消息
- 2 个嵌套循环的时间复杂度
- 给定使用 C++ 或 C,我如何测量在 linux 下进行线程切换需要多长时间?可能吗?
- asio::read() 需要很长时间,使用 asio::write 没有问题
- 将线程锁定很长时间
- 正在等待在非阻塞文件描述符上长时间运行ioctl
- 即使长时间等待,C++线程也不会加入
- 连接() 在连接被拒绝时长时间挂起
- 带有 if 语句的嵌套循环的时间复杂度
- 在关闭应用程序期间正确关闭线程,该线程可能会运行很长时间的循环
- 一个循环,可以打印所有项目(无论链条多长时间) *指针
- 断开循环,超过长时间的未签名
- 为什么具有多个嵌套循环的代码可以在 GCC 上立即完成,但在 VS 上需要很长时间
- 如何向编译器提供有关循环运行最长时间的提示
- 为什么for循环要花这么长时间
- 开始一个for循环需要多长时间