【发布时间】:2016-11-20 23:23:18
【问题描述】:
您会看到使用 Core Python 方法和 Numpy 方法创建了两个相等的数组:
from time import time
import numpy as np
a = [3] * 100000
b = np.array(a)
问题是,Numpy 在填充过程中怎么可能比 Core Python 方法快:
填充:
st = time()
for i in range(len(a)):
a[i] = 0
et = time()
print "Core Python need %f seconds" % (et-st)
st = time()
b.fill(0)
et = time()
print "Numpy need %f seconds" % (et-st)
结果:
Core Python need 0.014000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.014000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.001000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.001000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.014000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.013000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.014000 seconds
Numpy need 0.000000 seconds
>>> ================================ RESTART ================================
>>>
Core Python need 0.014000 seconds
Numpy need 0.000000 seconds
>>>
【问题讨论】:
-
有趣的问题。也许数组和列表不是一回事? +Core Python 必须通过循环。
Fill可能会以更有效的方式做到这一点, -
数组是连续的内存块,列表不是。用特定值填充连续的内存块很容易,尤其是
0,用相同的值填充列表要“更难”。 -
@Holt 你的意思是:在 python 中,一个 100,000 个元素的列表可能在不同的内存位置使用不同的小块,而对于数组来说它是一个大块?有什么规范吗?
-
执行
a[:] = [0]*len(a)可能比显式的for循环更快。 -
@EbraHim 如果您熟悉 C/C++ 等语言,您可以将 numpy 数组视为“
ints 的数组”,将 python 列表视为“指向int的指针数组” .
标签: python python-2.7 numpy