是这样的,我写了一段这样的代码:
import torch
import time
def test_performance():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# 预热
for i in range(3):
a = torch.randn(2000, 2000, device=device)
b = torch.randn(2000, 2000, device=device)
c = a @ b
torch.cuda.synchronize() if device.type == 'cuda' else None
# 测试 1: 大矩阵运算
print("\n=== 大矩阵测试 (5000x10000 @ 10000x5000) ===")
# GPU 测试
start_time = time.time()
for i in range(100):
a = torch.randn(5000, 10000, device=device)
b = torch.randn(10000, 5000, device=device)
c = a @ b
torch.cuda.synchronize() if device.type == 'cuda' else None
gpu_time = time.time() - start_time
print(f"GPU 100 次时间: {gpu_time:.4f} 秒")
# CPU 测试 (只做1次,因为太慢了)
if device.type == 'cuda':
start_time = time.time()
a = torch.randn(5000, 10000, device='cpu')
b = torch.randn(10000, 5000, device='cpu')
c = a @ b # 只做一次
cpu_time = time.time() - start_time
print(f"CPU 单次时间: {cpu_time:.4f} 秒")
print(f"GPU 比 CPU 快约: {cpu_time/(gpu_time/100):.1f} 倍")
# 测试 2: 中等矩阵运算
print("\n=== 中等矩阵测试 (2000x2000 @ 2000x2000) ===")
# GPU 测试
start_time = time.time()
for i in range(100):
a = torch.randn(2000, 2000, device=device)
b = torch.randn(2000, 2000, device=device)
c = a @ b
torch.cuda.synchronize() if device.type == 'cuda' else None
gpu_time_medium = time.time() - start_time
print(f"GPU 时间: {gpu_time_medium:.4f} 秒")
# CPU 测试
start_time = time.time()
for i in range(100):
a = torch.randn(2000, 2000, device='cpu')
b = torch.randn(2000, 2000, device='cpu')
c = a @ b
cpu_time_medium = time.time() - start_time
print(f"CPU 时间: {cpu_time_medium:.4f} 秒")
print(f"GPU 比 CPU 快约: {cpu_time_medium/gpu_time_medium:.1f} 倍")
if __name__ == "__main__":
test_performance()在 NVIDIA RTX A5000 上面的战绩!
=== 大矩阵测试 (5000x10000 @ 10000x5000) ===
GPU 时间: 3.1369 秒
CPU 单次时间: 0.9508 秒
GPU 比 CPU 快约: 30.3 倍
=== 中等矩阵测试 (2000x2000 @ 2000x2000) ===
GPU 时间: 0.1027 秒
CPU 时间: 3.7525 秒
GPU 比 CPU 快约: 36.6 倍大家想一想,假如洛谷上线 pytorch 与 CUDA,那以后矩阵快速幂或者大量矩阵乘法…
反观苹果的 MPS,一言难尽啊