在 Google Colab 上获得相同的 cpu 和 gpu 运行时间

问题描述 投票:0回答:2

所以我一直在使用 Colab 来进行我的学士学位深度学习项目。当我在 colab 上运行提供的示例来测试 cpu 和 gpu 之间的比较速度时,它工作正常,但是当我尝试使用自己的代码时,我得到了两者相同的运行时间。我正在进行的任务只是使用

PIL.Image
包将 1000 张 jpg 图像转换为 RGB 值。使用 GPU 时运行时间不是应该更快吗?或者只有在运行深度学习模型时才会出现这种情况?请在下面找到我使用的代码:

import pandas as pd
import tensorflow as tf
import timeit

device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
  raise SystemError('GPU device not found')
print('Found GPU at: {}'.format(device_name))

def cpu():
  dataset = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/user_01.xlsx")
  classes = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/Classes.xlsx")
  classes = list(np.array(classes).flatten())
  labels = np.array(dataset["Class"])
  labels = [classes.index(x) for x in labels]

  '''
  All the photos filename in an array
  '''
  files = np.array(dataset["Photo"])
  imgDir = "/content/drive/My Drive/BachelorProject/images_routine_users/user_01/user1_01/"
  with tf.device('/cpu:0'):
    files = np.array([convertToRGB(imgDir+x) for x in files[0:100]])

  img_width, img_height = 32, 32
  input_shape = (img_width, img_height, 3)

def gpu():
  dataset = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/user_01.xlsx")
  classes = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/Classes.xlsx")
  classes = list(np.array(classes).flatten())
  labels = np.array(dataset["Class"])
  labels = [classes.index(x) for x in labels]

  '''
  All the photos filename in an array
  '''
  files = np.array(dataset["Photo"])
  imgDir = "/content/drive/My Drive/BachelorProject/images_routine_users/user_01/user1_01/"
  with tf.device('/device:GPU:0'):
    files = np.array([convertToRGB(imgDir+x) for x in files[0:100]])

  img_width, img_height = 32, 32
  input_shape = (img_width, img_height, 3)

cpu()
gpu()

print('CPU (s):')
cpu_time = timeit.timeit('cpu()', number=10, setup="from __main__ import cpu")
print(cpu_time)
print('GPU (s):')
gpu_time = timeit.timeit('gpu()', number=10, setup="from __main__ import gpu")
print(gpu_time)
print('GPU speedup over CPU: {}x'.format(int(cpu_time/gpu_time)))

我得到的输出如下:

Found GPU at: /device:GPU:0
CPU (s):
167.21270494400005
GPU (s):
166.9953728999999
GPU speedup over CPU: 1x

这本质上是说 cpu 和 gpu 的运行时是相同的。希望听到您对此有何看法。谢谢

python tensorflow google-colaboratory
2个回答
0
投票

Tensorflow 设备设置不会影响非 Tensorflow 操作。

也就是说,Tensorflow 现在拥有自己的 numpy API,可以使用为 Tensorflow 设置的设备,例如

with tf.device('/device:GPU:0')

新的 api 可以像 numpy 一样使用

import tensorflow.experimental.numpy as tnp

这里还有一篇不错的博客文章,介绍了新 api 与普通(CPU)numpy 的性能比较。

这是一个相关问题,关于在 Colab 上使用普通 Python 的 GPU。


0
投票
  1. 当我使用colab时,如果我忘记选择TPU/GPU,结果会变得相同(CPU模式)。
  2. 下面是我的链接(01_Lecture 17_BM.ppt 和 02_Code/17_BM.zip,包含 colab 代码和 NVIDIA RTX Titan 的本地代码)https://github.com/peterhchen/AIU_CS512_DL/tree/main/000_Lecture_Project/week07
© www.soinside.com 2019 - 2024. All rights reserved.