简介讨论
本答案主要讲解如何利用高效的计算机图形处理器(GPU
)来解决所述问题。问题中给出的解决方案代码如下:
[~, loc] = sort(A(:,2));
SortedA = A(loc,:);
这个问题基本上可以分为两部分:
- 选择第二列,对它们进行排序并获得排序后的索引。
- 使用排序后的索引来索引输入矩阵的行。
现在,
Part 1
是计算密集型的,可以移植到
GPU
上,但是
Part 2
是索引工作,可以在
CPU
上完成。
建议的解决方案
所以,考虑到这些因素,一个高效的
GPU
解决方案如下:
gA = gpuArray(A(:,2)); %// Port only the second column of input matrix to GPU
[~, gloc] = sort(gA); %// compute sorted indices on GPU
SortedA = A(gather(gloc),:); %// get the sorted indices back to CPU with `gather`
%// and then use them to get sorted A
基准测试
下面介绍了用于将 GPU
版本与原始解决方案进行比较的基准测试代码,但需要注意,由于我们在不同的硬件上运行 GPU
代码,与原始运行在 CPU
上的解决方案相比,基准测试结果可能因系统而异。
以下是基准测试代码 -
N = 3000000;
A = rand(N,3);
disp('------------------ With original solution on CPU')
tic
[~, loc] = sort(A(:,2));
SortedA = A(loc,:);
toc, clear SortedA loc
disp('------------------ With proposed solution on GPU')
tic
gA = gpuArray(A(:,2));
[~, gloc] = sort(gA);
SortedA = A(gather(gloc),:);
toc
以下是基准测试结果:
------------------ With original solution on CPU
Elapsed time is 0.795616 seconds.
------------------ With proposed solution on GPU
Elapsed time is 0.465643 seconds.
如果您有足够好的 GPU
,那么现在是尝试使用 GPU
来解决排序问题的最佳时机,特别是MATLAB提供了如此简单的 GPU
端口解决方案。
系统配置
MATLAB Version: 8.3.0.532 (R2014a)
Operating System: Windows 7
RAM: 3GB
CPU Model: Intel® Pentium® Processor E5400 (2M Cache, 2.70 GHz)
GPU Model: GTX 750Ti 2GB
gpuArray
,但是你有一张足够好的GPU来处理吗? - Divakar