2012-03-14 73 views
4

我跑了一個簡單的速度測試,比較numpy和Python列表的理解,顯然列表理解更快。那是對的嗎?numpy vs list comprehension,哪個更快?

import sys, numpy 
from datetime import datetime 

def numpysum(n): 
    a = numpy.arange(n) ** 2 
    b = numpy.arange(n) ** 3 
    return a + b 

def pythonsum(n): 
    a = [i ** 2 for i in range(n)] 
    b = [i ** 3 for i in range(n)] 
    return [a[i] + b[i] for i in range(n)] 

size = 10 
start = datetime.now() 
c1 = pythonsum(size) 
delta1 = datetime.now() - start 

start = datetime.now() 
c2 = numpysum(size) 
delta2 = datetime.now() - start 

print c1 
print c2 

print delta1 
print delta2 

回答

14

我想你可能要考慮不同的測試參數:與NumPy的VS列表理解時序

In [39]: %timeit pythonsum(10) 
100000 loops, best of 3: 8.41 us per loop 

In [40]: %timeit pythonsum(100) 
10000 loops, best of 3: 51.9 us per loop 

In [41]: %timeit pythonsum(1000) 
1000 loops, best of 3: 451 us per loop 

In [42]: %timeit pythonsum(10000) 
100 loops, best of 3: 17.9 ms per loop 

In [43]: %timeit numpysum(10) 
100000 loops, best of 3: 13.4 us per loop 

In [44]: %timeit numpysum(100) 
100000 loops, best of 3: 17 us per loop 

In [45]: %timeit numpysum(1000) 
10000 loops, best of 3: 50.3 us per loop 

In [46]: %timeit numpysum(10000) 
1000 loops, best of 3: 385 us per loop 

比:

10:0.6X

100:3.1 x

1000:9x

10000:46X

因此,numpy的是大N快得多。

10

您的size太小。我再次嘗試size=1000000,numpy的表現理解度超過了9x。

我猜numpy的具有更高的設置開銷,但在一般的非平凡輸入尺寸(10絕對是微不足道的),你可以期望它至少是一樣快的列表理解,在大多數情況下多更快。