【发布时间】:2017-03-23 02:43:04
【问题描述】:
目前我有点惊讶这需要这么长时间。我想计算矩阵元素的总和,由它们到对角线的距离加权。方阵只包含非负整数元素。
我的代码
#!/usr/bin/env python
"""Calculate a score for a square matrix."""
import random
random.seed(0)
def calculate_score(cm):
"""
Calculate a score how close big elements of cm are to the diagonal.
Examples
--------
>>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
>>> calculate_score(cm)
32
"""
score = 0
for i, line in enumerate(cm):
for j, el in enumerate(line):
score += el * abs(i - j)
return score
def main(n):
import time
import numpy as np
score_calculations = 10**3
t = 0
for step in range(score_calculations):
cm = np.random.randint(0, 150000, size=(n, n))
t0 = time.time()
calculate_score(cm)
t1 = time.time()
t += (t1 - t0)
print("{:0.2f} scores / sec".format(score_calculations / t))
if __name__ == '__main__':
main(369)
分析
当前代码仅给出 32.47 分数/秒。 kernprof -l -v main.py 给出以下结果:
我尝试循环遍历元素本身(循环中的range(n)),但这将速度降低到只有 20.02 分/秒。
Wrote profile results to main.py.lprof
Timer unit: 1e-06 s
Total time: 109.124 s
File: main.py
Function: calculate_score at line 9
Line # Hits Time Per Hit % Time Line Contents
==============================================================
9 @profile
10 def calculate_score(cm):
11 """
12 Calculate a score how close big elements of cm are to the diagonal.
13
14 Examples
15 --------
16 >>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
17 >>> calculate_score(cm)
18 32
19 """
20 1000 619 0.6 0.0 score = 0
21 370000 180693 0.5 0.2 for i, line in enumerate(cm):
22 136530000 43691655 0.3 40.0 for j, el in enumerate(line):
23 136161000 65250190 0.5 59.8 score += el * abs(i - j)
24 1000 386 0.4 0.0 return score
我不确定是否有什么可以让这更快,因为代码似乎很简单。
【问题讨论】:
-
如果你想要numpy的好处,不要写循环
-
嗯,你不应该避免循环遍历 numpy 数组吗?构建一个单独的权重矩阵并找到点积不是更好吗?
-
为了获得额外的提升,缓存权重。
标签: python performance numpy