要测试Python中GPU的性能,你可以使用以下方法:
使用PyTorch:
import torch
检查GPU是否可用
if torch.cuda.is_available():
device = torch.device('cuda')
print('Using device:', device)
如果GPU可用,可以运行一些GPU上的操作
例如,创建一个简单的张量并将其移动到GPU
tensor = torch.randn(10, 10).cuda()
else:
device = torch.device('cpu')
print('Using device:', device)
使用ONNX Runtime:
如果你要测试模型的推理时间,并且想要在GPU上运行,你需要安装`onnxruntime-gpu`。
pip install onnxruntime-gpu
然后,你可以使用以下代码测试推理时间:
import onnxruntime as ort
加载ONNX模型
session = ort.InferenceSession('model.onnx')
准备输入数据
input_data = ... 你的输入数据
运行推理
start_time = time.time()
outputs = session.run(None, {'input': input_data})
end_time = time.time()
输出推理时间
print('Inference time:', end_time - start_time)
使用NVIDIA Management Library (nvidia-ml-py):
这个库允许你查询NVIDIA GPU的信息。
import pynvml
初始化nvidia-ml
pynvml.nvmlInit()
获取GPU信息
device_count = pynvml.nvmlDeviceGetCount()
for i in range(device_count):
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
print('Device name:', pynvml.nvmlDeviceGetName(handle))
print('Driver version:', pynvml.nvmlSystemGetDriverVersion())
print('Memory usage:', pynvml.nvmlDeviceGetMemoryInfo(handle).used / (1024 3), 'GB')
确保你的环境已经安装了适当的CUDA和cuDNN版本,以便PyTorch和ONNX Runtime可以利用GPU。