版本比较
CUDA 的 TensorCore 还是太超模了!
正文
增加 10 行删除 8 行
4 行未改动5678991011121314151516171718192020212223242526272829303031323334353637383940404142434344454647484950515253535455565720 行未改动787980818283844 行未改动
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')20 行未改动CPU 时间: 3.7525 秒GPU 比 CPU 快约: 36.6 倍```
大家想一想,假如洛谷上线 pytorch 与 CUDA,那以后矩阵快速幂或者大量矩阵乘法...
反观苹果的 MPS,一言难尽啊