跳到正文

个人记录

CUDA 的 TensorCore 还是太超模了!

__youzimo2014__约 5 分钟
原文

这是 2025年10月18日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年2月21日
篇幅
约 5 分钟

版本

  1. v3当前
  2. v2
  3. v1

是这样的,我写了一段这样的代码:

Python
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 倍

反观苹果的 MPS,一言难尽啊