我试图使用这个非常简单的脚本来测试 numpy 的性能:
import numpy as np
import argparse
from timeit import default_timer as timer
p = argparse.ArgumentParser()
p.add_argument("--N", default=1000, type=int, help="size of matrix A")
p.add_argument(
"--repeat", default=1000, type=int, help="perform computation x = A*b repeat times"
)
args = p.parse_args()
np.random.seed(0)
A = np.random.rand(args.N, args.N)
b = np.random.rand(args.N)
x = np.zeros(args.N)
ts = timer()
for i in range(args.repeat):
x[:] = A.dot(b)
te = timer()
gbytes = 8.0 * (args.N**2 + args.N * 2) * 1e-9
print("bandwidth: %.2f GB/s" % (gbytes * args.repeat / (te - ts)))
它所做的是创建一个随机密集矩阵,执行矩阵向量乘法
repeat
次,并计算这种操作的平均带宽,我认为这包括内存读取、计算和内存写入。然而,当我在我的笔记本电脑上运行这个脚本时,每次运行的结果差异很大:
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 93.64 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 99.15 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 95.08 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 77.28 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 56.90 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 63.87 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 85.43 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 95.69 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 93.91 GB/s
~/toys/python ❯ python numpy_performance.py --N 8000 --repeat 100
bandwidth: 101.99 GB/s
这种行为是预期的吗?如果是这样,如何解释?谢谢!
不稳定的结果可能有多种原因,CPU 不稳定是因为没有为您的独特进程配置,您可能有其他进程干扰您的运行,以及可能扰乱冷却之间运行的热节流
你可以做的一件事是进行多次运行然后平均结果