【发布时间】:2021-02-07 21:43:50
【问题描述】:
为了提高我的项目的性能,我使用 tf.function 编写了一个函数来替换一个不使用 tf.function 的函数。结果是,在启用 GPU 时,纯 python 代码的运行速度比 tf.funtion 快得多(快 100 倍)。在 CPU 上运行时,TF 仍然较慢,但仅慢 10 倍。我错过了什么吗?
@tf.function
def test1(cond):
xp = tf.constant(0)
yp = tf.constant(0)
stride = tf.constant(10)
patches = tf.TensorArray(
tf.int32, size=tf.cast((cond / stride + 1) * (cond / stride + 1), dtype=tf.int32), dynamic_size=False, clear_after_read=False)
i = tf.constant(0)
while tf.less_equal(yp, cond):
while tf.less_equal(xp, cond):
xp = tf.add(xp, stride)
patches = patches.write(i, xp)
i += 1
xp = tf.constant(0)
yp = tf.add(yp, stride)
return patches.stack()
def test2(cond):
xp = 0
yp = 0
stride = 10
i = 0
patches = []
while yp <= cond:
while xp <= cond:
xp += stride
patches.append(xp)
xp = 0
yp += stride
return patches
当 cond 很大(例如 5000 或更大)时,这一点特别明显
更新:
我找到了this 和this。正如我所料,TensorArray 的性能似乎很差,而且,就我而言,解决方案是用其他张量计算替换 TensorArray 和循环(在这种情况下,我使用了 tf.image.extract_patches 等)。通过这种方式,它实现了比普通 python 代码快 3 倍的性能。
【问题讨论】:
标签: python tensorflow