我试图在我的GPU的Matlab中减去两个“不同”大小的矩阵。
a = randn(87,1,10,'single','gpuArray');
b = randn(87,100000,1,'single','gpuArray');
dev = gpuDevice;
tic
out1 = a-b;
wait(dev)
toc
tic
a = repmat(a,[1 size(b,2) 1]);
b = repmat(b,[1 1 size(a,3)]);
out2 = a-b;
wait(dev)
toc
如您所见,沿第二和第三个维度存在隐式扩展。通常,隐式扩展比复制矩阵快得多。但是,在这种情况下,它会给出结果:
Elapsed time is 0.033324 seconds.
Elapsed time is 0.018052 seconds.
这令人困惑,因为复制矩阵比仅让隐式扩展处理差异要快得多。我在CPU上对此进行了测试,并得到:
Elapsed time is 0.078726 seconds.
Elapsed time is 0.356435 seconds.
这到底是怎么回事?为什么隐式扩展这么慢?
我在Matlab 2018b和2019a预发行版上对此进行了测试,并在两者上均获得了此结果。
编辑:由于流行的需求,我在两者上都使用了timeit和gputimeit函数,这再次证实了我的结果
clear
close all
a = randn(87,1,10,'single','gpuArray');
b = randn(87,100000,1,'single','gpuArray');
dev = gpuDevice;
disp(gputimeit(@() a-b))
disp(gputimeit(@() a>b))
t1 = gputimeit(@() repmat(a,[1 size(b,2) 1]))+gputimeit(@() repmat(b,[1 1 size(a,3)]));
a = repmat(a,[1 size(b,2) 1]);
b = repmat(b,[1 1 size(a,3)]);
disp(t1+gputimeit(@() a-b))
disp(gputimeit(@() a>b))
clear
close all
a = randn(87,1,10,'single');
b = randn(87,100000,1,'single');
disp(timeit(@() a-b))
disp(timeit(@() a>b))
t1 = timeit(@() repmat(a,[1 size(b,2) 1]))+timeit(@() repmat(b,[1 1 size(a,3)]));
a = repmat(a,[1 size(b,2) 1]);
b = repmat(b,[1 1 size(a,3)]);
disp(t1+timeit(@() a-b))
disp(timeit(@() a>b))
时间是:
0.0249880485773384
0.0191386963821538
0.0159509649972431
0.00518230250048866
0.0980248506300088
0.0545817410501994
0.283484452903233
0.0540456719899175