use*_*015 5 python matlab for-loop
我在同一台机器上运行python 2.7和matlab R2010a,什么都不做,它给我10倍的速度
我在网上看了,听说它应该是同一个订单.Python将在for循环中进一步减慢,就像语句和数学运算符一样
我的问题:这是现实吗?还是有其他方式让他们以相同的速度顺序?
这是python代码
import time
start_time = time.time()
for r in xrange(1000):
for c in xrange(1000):
continue
elapsed_time = time.time() - start_time
print 'time cost = ',elapsed_time
Run Code Online (Sandbox Code Playgroud)
Output: time cost = 0.0377440452576
这是matlab代码
tic
for i = 1:1000
for j = 1:1000
end
end
toc
Run Code Online (Sandbox Code Playgroud)
Output: Escaped time is 0.004200 seconds
发生这种情况的原因与JIT编译器有关,它正在优化MATLAB for循环.您可以使用feature accel off和禁用/启用JIT加速器feature accel on.禁用加速器时,时间会发生显着变化.
MATLAB with accel on: Elapsed time is 0.009407 seconds.
加载MATLAB的MATLAB: Elapsed time is 0.287955 seconds.
蟒蛇: time cost = 0.0511920452118
因此,JIT加速器直接导致您注意到的加速.您应该考虑另一件事,这与您定义迭代索引的方式有关.在MATLAB和python这两种情况下,您都使用迭代器来定义循环.在MATLAB中,您可以通过添加方括号([])来创建实际值,并在python中使用range而不是xrange.当您进行这些更改时
% MATLAB
for i = [1:1000]
for j = [1:1000]
# python
for r in range(1000):
for c in range(1000):
Run Code Online (Sandbox Code Playgroud)
时代变了
MATLAB with accel on: Elapsed time is 0.338701 seconds.
加载MATLAB的MATLAB: Elapsed time is 0.289220 seconds.
蟒蛇: time cost = 0.0606048107147
最后一个考虑因素是如果要在循环中添加快速计算.即t=t+1.然后时代变了
MATLAB with accel on: Elapsed time is 1.340830 seconds.
关闭加速的MATLAB :( Elapsed time is 0.905956 seconds.关闭更快)
蟒蛇: time cost = 0.147221088409
我认为这里的道德是开箱即用的for循环的计算速度与极其简单的循环相当,具体取决于具体情况.但是,python中还有其他一些数值工具可以显着提高速度,numpy和PyPy到目前为止已经提出来了.
如果 Python 执行性能对你来说真的很重要,你可以看看PyPy
我做了你的测试:
import time
for a in range(10):
start_time = time.time()
for r in xrange(1000):
for c in xrange(1000):
continue
elapsed_time = time.time()-start_time
print elapsed_time
Run Code Online (Sandbox Code Playgroud)
使用标准 Python 2.7.3,我得到:
0.0311839580536
0.0310959815979
0.0309510231018
0.0306520462036
0.0302460193634
0.0324130058289
0.0308878421783
0.0307397842407
0.0304911136627
0.0307500362396
Run Code Online (Sandbox Code Playgroud)
然而,使用 PyPy 1.9.0(对应于 Python 2.7.2),我得到:
0.00921821594238
0.0115230083466
0.00851202011108
0.00808095932007
0.00496387481689
0.00499391555786
0.00508499145508
0.00618195533752
0.005126953125
0.00482988357544
Run Code Online (Sandbox Code Playgroud)
PyPy 的加速确实令人惊叹,并且当其 JIT 编译器优化超过其成本时才真正变得可见。这也是我引入额外的 for 循环的原因。对于此示例,绝对不需要修改代码。
| 归档时间: |
|
| 查看次数: |
6134 次 |
| 最近记录: |