Tensorflow中检查GPU及其性能

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)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容