<分区>
我在 C++ 中有一个嵌套的 for 循环:
for(i=0;i<10000000;i++)
{
for(j=0;j<999999;j++)
{
//execute something
}
}
我想知道:
- 此代码完成运行所需的小时数。
- 使用具有更多 RAM 和内核的机器是否会提高运行时间?
- 我选择的语言(MATLAB、Python、C/C++)将如何影响运行时?
<分区>
我在 C++ 中有一个嵌套的 for 循环:
for(i=0;i<10000000;i++)
{
for(j=0;j<999999;j++)
{
//execute something
}
}
我想知道:
最佳答案
如果你只是要求测量你可以使用的时间
#include <ctime>
int start_s=clock();
// code
int stop_s=clock();
cout << "time (in milis): " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000;
但如果您想知道如果获得更多 ram 或更多 cpu 内核,这个运行时是否会更好,这就是您所需要的:
简短的回答:它取决于“//执行某事” block
长答案: 它不直接取决于循环边界是什么,它只取决于你在嵌套循环中做了什么 这里有一些双循环的例子来证明这一点
请注意,核心数与运行时间无关,因为默认情况下代码未并行化
sum = 0;
for(i=0;i<10000000;i++)
for(j=0;j<999999;j++)
sum+=1;
int arr[10000000][999999];
arr[0][0] = 0;
for(i=1;i<10000000;i++)
for(j=1;j<999999;j++)
arr[i][j]=arr[i-1][j-1];
for(i=0;i<10000000;i++)
for(j=0;j<999999;j++)
cout << "yes";
ofstream file;
file.open ("out.txt");
for(i=0;i<10000000;i++)
for(j=0;j<999999;j++)
file << "Writing to the file.\n";
关于c++ - 如何从理论上计算嵌套循环的运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259628/