matlab python c的循环比较
matlab python c的循环比较
最近在matlab中进行一个回归实验中需要使用一个三层for循环,结果速度很慢,让我犹豫是否该切换到python上做此项工作,因此决定做一个循环运行时间的比较
matlab中的循环
[plain]
function test_speed()
tic;
for i=1:10
for j=1:2000
for k=1:20000
a = i + j + k;
end
end
end
toc;
end
function test_speed()
tic;
for i=1:10
for j=1:2000
for k=1:20000
a = i + j + k;
end
end
end
toc;
end
运行时间为1.523684 秒。
[plain]
function test_speed()
tic;
for k=1:20000
for j=1:2000
for i=1:10
a = i + j + k;
end
end
end
toc;
end
function test_speed()
tic;
for k=1:20000
for j=1:2000
for i=1:10
a = i + j + k;
end
end
end
toc;
end
将上述循环次序从新排列后(外层循环次数更多),运行时间为3.322692秒。说明从网上某些资料说明的在matlab中要将循环次数更多的代码放到内层循环是有道理的。
python中的循环
[python]
import time;
i=1
ticks_b = time.time();
while(i < 10):
j=1
while(j < 2000):
k=1
while(k < 20000):
a = i + j + k
#print (i,j,k,a),
k += 1
j += 1
i += 1
ticks_e = time.time();
print (ticks_e-ticks_b,i,j,k,a);
import time;
i=1
ticks_b = time.time();
while(i < 10):
j=1
while(j < 2000):
k=1
while(k < 20000):
a = i + j + k
#print (i,j,k,a),
k += 1
j += 1
i += 1
ticks_e = time.time();
print (ticks_e-ticks_b,i,j,k,a);
看到输出的时间约为94.51399993896484秒,可见比matlab要慢得太多。
在调整循环次序排列(外层循环次数更多),运行时间为104.70000004768372。也体现出了应将循环次数更多的代码放到内层循环。
c中的循环
[cpp]
int _tmain(int argc, _TCHAR* argv[])
{
int a = 0;
DWORD b = ::GetTickCount();
for (int i=1; i<=10; ++i)
{
for (int j=1; j <= 2000; ++j)
{
for (int k=1; k <= 20000; ++k)
{
a = i + j + k;
}
}
}
printf ("%d %d\r\n", ::GetTickCount() - b, a);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 0;
DWORD b = ::GetTickCount();
for (int i=1; i<=10; ++i)
{
for (int j=1; j <= 2000; ++j)
{
for (int k=1; k <= 20000; ++k)
{
a = i + j + k;
}
}
}
printf ("%d %d\r\n", ::GetTickCount() - b, a);
return 0;
}
在debug下运行输出为998,在release下运行输出为312.
所以目前的结论是:还是继续在matlab中做实验吧,暂时忘掉python!
相关内容
- 暂无相关文章
评论关闭