python循环成本_python循环比matlab慢10倍

I run python 2.7 and matlab R2010a on the same machine, doing nothing, and it gives me 10x different in speed

I looked online, and heard it should be the same order.

Python will further slow down as if statement and math operator in the for loop

My question: is this the reality? or there is some other way let them in the same speed order?

Here is python code

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

Output: time cost = 0.0377440452576

Here is matlab code

tic

for i = 1:1000

for j = 1:1000

end

end

toc

Output: Escaped time is 0.004200 seconds

解决方案

The reason this is happening is related to the JIT compiler, which is optimizing the MATLAB for loop. You can disable/enable the JIT accelerator using feature accel off and feature accel on. When you disable the accelerator, the times change dramatically.

MATLAB with accel on: Elapsed time is 0.009407 seconds.

MATLAB with accel off: Elapsed time is 0.287955 seconds.

python: time cost = 0.0511920452118

Thus the JIT accelerator is directly causing the speedup that you are noticing. There is another thing that you should consider, which is related to the way that you defined the iteration indices. In both cases, MATLAB and python, you used Iterators to define your loops. In MATLAB you create the actual values by adding the square brackets ([]), and in python you use range instead of xrange. When you make these changes

% MATLAB

for i = [1:1000]

for j = [1:1000]

# python

for r in range(1000):

for c in range(1000):

The times become

MATLAB with accel on: Elapsed time is 0.338701 seconds.

MATLAB with accel off: Elapsed time is 0.289220 seconds.

python: time cost = 0.0606048107147

One final consideration is if you were to add a quick computation to the loop. ie t=t+1. Then the times become

MATLAB with accel on: Elapsed time is 1.340830 seconds.

MATLAB with accel off: Elapsed time is 0.905956 seconds. (Yes off was faster)

python: time cost = 0.147221088409

I think that the moral here is that the computation speeds of for loops, out-of-the box, are comparable for extremely simple loops, depending on the situation. However, there are other, numerical tools in python which can speed things up significantly, numpy and PyPy have been brought up so far.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值