【发布时间】:2019-08-09 19:32:42
【问题描述】:
我正在尝试决定是否应该同时或顺序处理几个相似但独立的问题(可能在不同的计算机上并行处理)。为了做出决定,我需要比较以下操作的 cpu 时间:
time_1 是计算 X(with shape (n,p)) @ b (with shape (p,1)) 的时间。
time_k 是计算X(形状为(n,p))@B(形状为(p,k))的时间。
其中 X、b 和 B 是随机矩阵。这两个操作之间的区别在于第二个矩阵的宽度。
天真地,我们期望 time_k = k x time_1。使用更快的矩阵乘法算法(Strassen 算法、Coppersmith–Winograd 算法),time_k 可能小于 k x time_1,但这些算法的复杂度仍然比我在实践中观察到的要大得多。因此我的问题是: 如何解释这两种计算在 cpu 时间方面的巨大差异?
我使用的代码如下:
import time
import numpy as np
import matplotlib.pyplot as plt
p = 100
width = np.concatenate([np.arange(1, 20), np.arange(20, 100, 10), np.arange(100, 4000, 100)]).astype(int)
mean_time = []
for nk, kk in enumerate(width):
timings = []
nb_tests = 10000 if kk <= 300 else 100
for ni, ii in enumerate(range(nb_tests)):
print('\r[', nk, '/', len(width), ', ', ni, '/', nb_tests, ']', end = '')
x = np.random.randn(p).reshape((1, -1))
coef = np.random.randn(p, kk)
d = np.zeros((1, kk))
start = time.time()
d[:] = x @ coef
end = time.time()
timings.append(end - start)
mean_time.append(np.mean(timings))
mean_time = np.array(mean_time)
fig, ax = plt.subplots(figsize =(14,8))
plt.plot(width, mean_time, label = 'mean(time\_k)')
plt.plot(width, width*mean_time[0], label = 'k*mean(time\_1)')
plt.legend()
plt.xlabel('k')
plt.ylabel('time (sec)')
plt.show()
【问题讨论】:
-
你的意思是什么?向我们展示您的困惑。
标签: python numpy matrix time multiplication