python array太慢,为什么numpy.array这么慢?

I am baffled by this

def main():

for i in xrange(2560000):

a = [0.0, 0.0, 0.0]

main()

$ time python test.py

real 0m0.793s

Let's now see with numpy:

import numpy

def main():

for i in xrange(2560000):

a = numpy.array([0.0, 0.0, 0.0])

main()

$ time python test.py

real 0m39.338s

Holy CPU cycles batman!

Using numpy.zeros(3) improves, but still not enough IMHO

$ time python test.py

real 0m5.610s

user 0m5.449s

sys 0m0.070s

numpy.version.version = '1.5.1'

If you are wondering if the list creation is skipped for optimization in the first example, it is not:

5 19 LOAD_CONST 2 (0.0)

22 LOAD_CONST 2 (0.0)

25 LOAD_CONST 2 (0.0)

28 BUILD_LIST 3

31 STORE_FAST 1 (a)

解决方案

Numpy is optimised for large amounts of data. Give it a tiny 3 length array and, unsurprisingly, it performs poorly.

Consider a separate test

import timeit

reps = 100

pythonTest = timeit.Timer('a = [0.] * 1000000')

numpyTest = timeit.Timer('a = numpy.zeros(1000000)', setup='import numpy')

uninitialised = timeit.Timer('a = numpy.empty(1000000)', setup='import numpy')

# empty simply allocates the memory. Thus the initial contents of the array

# is random noise

print 'python list:', pythonTest.timeit(reps), 'seconds'

print 'numpy array:', numpyTest.timeit(reps), 'seconds'

print 'uninitialised array:', uninitialised.timeit(reps), 'seconds'

And the output is

python list: 1.22042918205 seconds

numpy array: 1.05412316322 seconds

uninitialised array: 0.0016028881073 seconds

It would seem that it is the zeroing of the array that is taking all the time for numpy. So unless you need the array to be initialised then try using empty.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值