dav*_*ang 2 python gpu pytorch
这是我的代码(模拟前馈神经网络):
import torch
import time
print(torch.cuda.is_available()) # True
device = torch.device('cuda:0' )
a = torch.tensor([1,2,3,4,5,6]).float().reshape(-1,1)
w1 = torch.rand(120,6)
w2 = torch.rand(1,120)
b1 = torch.rand(120,1)
b2 = torch.rand(1,1).reshape(1,1)
start = time.time()
for _ in range(100000):
ans = torch.mm(w2, torch.mm(w1,a)+b1)+b2
end = time.time()
print(end-start) # 1.2725720405578613 seconds
a = a.to(device)
w1 = w1.to(device)
w2 = w2.to(device)
b1 = b1.to(device)
b2 = b2.to(device)
start = time.time()
for _ in range(100000):
ans = torch.mm(w2, torch.mm(w1,a)+b1)+b2
end = time.time()
print(end-start) # 5.6569812297821045 seconds
Run Code Online (Sandbox Code Playgroud)
我不知道如果我做了错误的方式还是什么,我怎么可以改变我的代码表明,GPU IS更快然后在矩阵乘法CPU?
原因可能有很多:
a
每次运行生成随机张量会更好这是 pytorch 论坛上的一个主题:https ://discuss.pytorch.org/t/cpu-faster-than-gpu/25343
你也应该使用更好的分析器,就像在这个线程中解释的那样:https ://discuss.pytorch.org/t/how-to-measure-time-in-pytorch/26964
归档时间: |
|
查看次数: |
418 次 |
最近记录: |