验证GPU有效性的python代码
时间: 2024-09-29 07:11:33 浏览: 43
验证GPU有效性通常通过NVIDIA CUDA库的Python接口,例如`torch`或`cupy`,来进行。以下是一个简单的例子,使用PyTorch来检查CUDA是否可用以及GPU的状态:
```python
# 首先确保已经安装了PyTorch和cuda相关的包
try:
import torch
except ImportError:
print("PyTorch not installed. Please install it for GPU verification.")
else:
# 检查是否有可用的CUDA设备
if torch.cuda.is_available():
device = torch.device("cuda")
print(f"CUDA is available. Running on {device}...")
# 获取当前GPU的一些信息,如名称、显存大小等
print(f"Device name: {torch.cuda.get_device_name(0)}")
print(f"Memory allocated: {torch.cuda.memory_allocated(device) / (1024 ** 3):.2f} GB")
print(f"Memory cached: {torch.cuda.memory_cached(device) / (1024 ** 3):.2f} GB")
print("\nCurrent GPU status:")
print(torch.cuda.memory_summary())
else:
print("CUDA is NOT available or the machine does not have a CUDA-capable GPU.")
阅读全文