Tensorflow中数据类型为张量,可运行在CPU,GPU或TPU设备上,但numpy中的array数据只能运行在CPU中,因此具有更高的计算效率。
Tensorflow编程中,一般无需指定设备,Tensorflow会自动调用所有可用资源进行计算,优先使用GPU,没有则使用CPU。
import tensorflow as tf
import timeit
print('version of TF:',tf.__version__)
print(tf.test.is_gpu_available())
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print('GPU devices:')
print(gpus)
print('CPU devices:')
print(cpus)
def cpu_run():
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([1000,2000])
cpu_b = tf.random.normal([2000,1000])
c = tf.matmul(cpu_a, cpu_b)
return c
def gpu_run():
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([1000,2000])
gpu_b = tf.random.normal([2000,1000])
c = tf.matmul(gpu_a, gpu_b)
return c
k1 = 10
cpu_time = timeit.timeit(cpu_run, number=k1)
gpu_time = timeit.timeit(gpu_run, number=k1)
print('cpu time of k=10 :',cpu_time, 'gpu time of k=10 :',gpu_time)
k2 = 100
cpu_time = timeit.timeit(cpu_run, number=k2)
gpu_time = timeit.timeit(gpu_run, number=k2)
print('cpu time of k=100 :',cpu_time, 'gpu time of k=100 :',gpu_time)
k3 = 1000
cpu_time = timeit.timeit(cpu_run, number=k3)
gpu_time = timeit.timeit(gpu_run, number=k3)
print('cpu time of k=1000:',cpu_time, 'gpu time of k=1000:',gpu_time)
网友评论