首页 > 解决方案 > 为什么在 PyTorch 中在 GPU 上创建单个张量需要 2.5 秒?

问题描述

我只是在浏览 PyTorch 的初学者教程,并注意到与其他方法相比,在 GPU 上放置张量(基本上与 numpy 数组相同)的许多不同方法中的一种花费了令人怀疑的长数量

import time
import torch

if torch.cuda.is_available():
    print('time =', time.time())
    x = torch.randn(4, 4)
    device = torch.device("cuda")
    print('time =', time.time())
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU  => 2.5 secs??
    print('time =', time.time())
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!
    a = torch.ones(5)
    print(a.cuda())
    print('time =', time.time())
else:
    print('I recommend you get CUDA to work, my good friend!')

输出(只是时间):

time = 1551809363.28284
time = 1551809363.282943
time = 1551809365.7204516  # (!)
time = 1551809365.7236063

版本详情:

1 CUDA device: GeForce GTX 1050, driver version 415.27
CUDA          = 9.0.176
PyTorch       = 1.0.0
cuDNN         = 7401
Python        = 3.5.2
GCC           = 5.4.0
OS            = Linux Mint 18.3
Linux kernel  = 4.15.0-45-generic

正如您所看到的,这一个操作(“y = ...”)比其余操作(0.003 秒)花费的时间(2.5 秒)要长得多。我对此感到困惑,因为我希望所有这些方法基本上都能做到这一点。我已经尝试确保该行中的类型是 32 位或具有不同的形状,但这并没有改变任何东西。

标签: python-3.xpytorch

解决方案


当我重新排序命令时,顶部的任何命令都需要 2.5 秒。所以这让我相信这里发生了设备的一次性设置延迟,未来的 GPU 分配会更快。


推荐阅读