import tensorflow as tf
def check_gpu():
try:
# 打印 TensorFlow 版本
print(f"TensorFlow 版本: {tf.__version__}")
# 检查是否检测到 GPU
gpus = tf.config.list_physical_devices('GPU')
if gpus:
print(f"检测到 {len(gpus)} 个 GPU:")
for gpu in gpus:
print(f"- {gpu.name}")
# 测试 GPU 是否可以被 TensorFlow 正常使用
print("正在测试 GPU 的可用性...")
with tf.device('/GPU:0'):
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
b = tf.constant([[5.0, 6.0], [7.0, 8.0]])
result = tf.matmul(a, b)
print(f"GPU 测试成功,计算结果: \n{result.numpy()}")
else:
print("未检测到 GPU,TensorFlow 将使用 CPU。")
except Exception as e:
print(f"GPU 检查失败: {e}")
if __name__ == "__main__":
check_gpu()
输出结果
