<p>正如我在评论中提到的,你的解决方案并不是真正的最优,比较不理想的方法也没有实际意义。在</p>
<p>一方面,迭代或索引NumPy数组的单个元素非常慢。我最近回答了一个包含很多细节的问题(如果你感兴趣,你可以看看:<a href="https://stackoverflow.com/a/44226069/5393381">"convert np array to a set takes too long"</a>)。因此,Python方法只需将<code>array</code>转换为<code>list</code>,就可以更快:</p>
<pre><code>def func():
sample = np.random.random_sample((100, 2))
disc1 = 0
n_sample = len(sample)
dim = sample.shape[1]
sample = sample.tolist() # converted to list
for i in range(n_sample):
prod = 1
for item in sample[i]:
sub = abs(item - 0.5)
prod *= 1 + 0.5 * sub - 0.5 * sub ** 2
disc1 += prod
disc2 = 0
for i, j in itertools.product(range(n_sample), range(n_sample)):
prod = 1
for k in range(dim):
a = 0.5 * abs(sample[i][k] - 0.5)
b = 0.5 * abs(sample[j][k] - 0.5)
c = 0.5 * abs(sample[i][k] - sample[j][k])
prod *= 1 + a + b - c
disc2 += prod
c2 = (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2
</code></pre>
<p>我还将<code>np.abs</code>调用替换为正常的<code>abs</code>。正常的<code>abs</code>开销更低!也改变了其他部分。最后,这比你最初的“正常”方法快了10-20倍。在</p>
<p>我还没有时间检查NumPy方法,@Divarkar已经包含了一个非常好和优化的方法。比较两种方法:</p>
^{pr2}$
<p>因此,一个优化的NumPy方法绝对可以击败“优化的”Python方法。它几乎快了100倍。如果您想要更快,您可以在纯python代码稍微修改过的版本上使用<a href="/questions/tagged/numba" class="post-tag" title="show questions tagged 'numba'" rel="tag">numba</a>:</p>
<pre><code>import numba as nb
@nb.njit
def func_numba():
sample = np.random.random_sample((100, 2))
disc1 = 0
n_sample = len(sample)
dim = sample.shape[1]
for i in range(n_sample):
prod = 1
for item in sample[i]:
sub = abs(item - 0.5)
prod *= 1 + 0.5 * sub - 0.5 * sub ** 2
disc1 += prod
disc2 = 0
for i in range(n_sample):
for j in range(n_sample):
prod = 1
for k in range(dim):
a = 0.5 * abs(sample[i,k] - 0.5)
b = 0.5 * abs(sample[j,k] - 0.5)
c = 0.5 * abs(sample[i,k] - sample[j,k])
prod *= 1 + a + b - c
disc2 += prod
return (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2
func_numba()
print('numba function time: ' ,
timeit.repeat('func_numba()', number=20, repeat=3, setup="from __main__ import func_numba"))
# numba function time: [0.003022848984983284, 0.0030429566279508435, 0.004060626777572907]
</code></pre>
<p>这几乎是一个因素8-10快于NumPy方法。在</p>