【发布时间】:2018-11-29 03:52:08
【问题描述】:
import tensorflow as tf
import numpy as np
from time import time
def print_timer(func):
start_time = time()
func()
end_time = time()
print(end_time - start_time)
N = 4
A = np.random.randn(N, 1000, 16000)
B = np.random.randn(N, 16000, 10)
sess = tf.Session()
A_ = tf.constant(A)
B_ = tf.constant(B)
def np_test():
r = np.empty([N, 1000, 10])
for i in range(N):
r[i] = np.matmul(A[i], B[i])
print_timer(lambda: np.matmul(A, B))
print_timer(lambda: sess.run(tf.matmul(A,B)))
当我运行这段代码时,我得到了如下结果:
1.3403866291046143
4.291470527648926
这是运行时间。
我不知道为什么 tensorflow.matmul 比 numpy.matmul 慢。 我在 P40 NVIDIA GPU 上运行此代码,我使用的 tensorflow 版本是 1.4。
当我尝试在 tensorflow 1.8 上运行此代码时,我得到了相同的结果。
如果 tensorflow 并行运行矩阵乘法,GPU 上的矩阵乘法的运行时间不应该比在 CPU 上运行的 numpy 上运行的运行时间快很多吗?
【问题讨论】:
-
复制数据到CPU不会增加很大的开销吗?我会尝试更长的操作,例如 100000 矩阵乘法。我可能完全错了。
-
对
A, B = tf.get_variable('v0', initializer=A), ...做同样的事情并为惊喜做好准备(没有 cudaMemcpy)。
标签: numpy tensorflow gpu