1. 程式人生 > >Matlab 應用GPU加速

Matlab 應用GPU加速

由於GPU近幾年地迅速發展,GPU在多執行緒計算等方面逐漸超越CPU成為計算的主力軍。而Matlab是常用的數學應用軟體,現在講解一下如何在Matlab中使用GPU加速計算

0. 必要條件

要想在Matlab中使用GPU加速有兩個必須的條件

  1. 計算機上安裝了NVIDIA顯示卡,目前AMD與Intel顯示是暫不支援的;
  2. 安裝NVIDIA顯示卡驅動。

1.給GPU傳輸資料

1.1 CPU的資料複製到GPU

在使用GPU計算的時候,只需要將CPU的資料複製到GPU中即可。

G = gpuArray(M);

上邊是對資料的名稱做了修改,也可以直接進行重新賦值。

M 
= gpuArray(M);

1.2 直接在GPU上設定資料:

A = zeros(10, 'gpuArray');

可以對0矩陣以及1矩陣直接進行復制,但是在程式後邊需要標註使用gpuArray。

r = gpuArray.rand(1, 100) % 一行,一百列

隨機矩陣的產生。

2.資料在GPU上運算

在GPU可以正常執行基本的運算,與正常矩陣計算方法相同

A=abs(A);

具體的可以執行的運算可以使用命令

methods(gpuArray)

進行檢視,Matlab可以在GPU執行的具體運算可以檢視附錄,附錄中是Matlab給出的結果。

3.GPU資料回傳

B = gather
(
A);

直接使用上邊的命令就能夠將GPU中的資料回傳給CPU。

4.使用技巧

4.1 如果沒有Nvidia顯示卡或者顯示卡驅動

如果沒有Nvidia顯示卡或者顯示卡驅動,會顯示下邊的提示。

這裡寫圖片描述

4.2 雙精度儘量轉換為單精度

在條件允許的情況下,儘量將計算過程中雙精度轉換為單精度。因為在GPU中單精度的計算速度明顯優於雙精度,在時間上會有很大的縮減。
附:單精度與上精度區別

資料型別 大小(位元組) 取值範圍 保留有效位數
單精度 4個位元組(32位) 3.4E-38~3.4E+38 7位
雙精度 8個位元組(64位) 1.7E-308~1.7E+308 16位

附錄

>> methods(gpuArray)

Methods for class gpuArray:

abs                   eq                    ipermute              quiver3               
accumarray            erf                   iradon                rad2deg               
acos                  erfc                  isaUnderlying         radon                 
acosd                 erfcinv               isbanded              rdivide               
acosh                 erfcx                 isdiag                real                  
acot                  erfinv                isempty               reallog               
acotd                 errorbar              isequal               realpow               
acoth                 existsOnGPU           isequaln              realsqrt              
acsc                  exp                   isequalwithequalnans  reducepatch           
acscd                 expint                isfinite              reducevolume          
acsch                 expm                  isfloat               regionprops           
all                   expm1                 ishermitian           rem                   
and                   eye                   isinf                 repelem               
angle                 ezcontour             isinteger             repmat                
any                   ezcontourf            islogical             reshape               
applylut              ezgraph3              ismember              rgb2gray              
area                  ezmesh                ismembertol           rgb2hsv               
arrayfun              ezmeshc               isnan                 rgb2ycbcr             
asec                  ezplot                isnumeric             ribbon                
asecd                 ezplot3               isocaps               roots                 
asech                 ezpolar               isocolors             rose                  
asin                  ezsurf                isonormals            rot90                 
asind                 ezsurfc               isosurface            round                 
asinh                 factorial             isreal                scatter               
assert                false                 issorted              scatter3              
atan                  feather               issparse              sec                   
atan2                 fft                   issymmetric           secd                  
atan2d                fft2                  istril                sech                  
atand                 fftfilt               istriu                semilogx              
atanh                 fftn                  kmeans                semilogy              
bandwidth             fill                  knnsearch             setdiff               
bar                   fill3                 ldivide               setxor                
bar3                  filter                le                    shiftdim              
bar3h                 filter2               legendre              shrinkfaces           
barh                  find                  length                sign                  
besselj               fix                   line                  sin                   
bessely               flip                  linspace              sind                  
beta                  flipdim               log                   single                
betainc               fliplr                log10                 sinh                  
betaincinv            flipud                log1p                 size                  
betaln                floor                 log2                  slice                 
bicg                  fplot                 logical               smooth3               
bicgstab              fprintf               loglog                sort                  
bicgstabl             full                  logspace              sortrows              
bitand                gamma                 lsqr                  sparse                
bitcmp                gammainc              lt                    spfun                 
bitget                gammaincinv           lu                    spones                
bitor                 gammaln               mat2gray              sprand                
bitset                gather                mat2str               sprandn               
bitshift              ge                    max                   sprandsym             
bitxor                gmres                 mean                  sprintf               
bsxfun                gop                   medfilt2              spy                   
bwdist                gpuArray              mesh                  sqrt                  
bwlabel               gradient              meshc                 stairs                
bwlookup              gt                    meshgrid              std2                  
bwmorph               head                  meshz                 stdfilt               
cast                  hist                  min                   stem                  
cat                   histc                 minres                stem3                 
cconv                 histcounts            minus                 stream2               
cdf2rdf               histeq                mldivide              stream3               
ceil                  histogram             mod                   streamline            
cgs                   horzcat               mode                  streamparticles       
chol                  hsv2rgb               movmean               streamribbon          
circshift             hypot                 movstd                streamslice           
clabel                idivide               movsum                streamtube            
classUnderlying       ifft                  movvar                stretchlim            
comet                 ifft2                 mpower                sub2ind               
comet3                ifftn                 mrdivide              subsasgn              
compass               im2double             mtimes                subsindex             
complex               im2int16              nan                   subspace              
cond                  im2single             ndgrid                subsref               
coneplot              im2uint16             ndims                 subvolume             
conj                  im2uint8              ne                    sum                   
contour               imabsdiff             nextpow2              superiorfloat         
contour3              imadjust              nnz                   surf                  
contourc              imag                  nonzeros              surfc                 
contourf              image                 norm                  surfl                 
contourslice          imagesc               normest               svd                   
conv                  imbothat              normxcorr2            svds                  
conv2                 imclose               not                   swapbytes             
convn                 imcomplement          nthroot               symmlq                
corr2                 imdilate              null                  tail                  
corrcoef              imerode               num2str               tan                   
cos                   imfill                numel                 tand                  
cosd                  imfilter              nzmax                 tanh                  
cosh                  imgaussfilt           ones                  tfqmr                 
cot                   imgaussfilt3          or                    times                 
cotd                  imgradient            padarray              transpose             
coth                  imgradientxy          pagefun               trapz                 
cov                   imhist                pareto                tril                  
csc                   imlincomb             patch                 trimesh               
cscd                  imnoise               pcg                   trisurf               
csch                  imopen                pcolor                triu                  
ctranspose            imreconstruct         pdist                 true                  
cummax                imregdemons           pdist2                typecast              
cummin                imregionalmax         permute               uint16                
cumprod               imregionalmin         pie                   uint32                
cumsum                imresize              pie3                  uint64                
curl                  imrotate              planerot              uint8                 
deg2rad               imrotate_old          plot                  uminus                
del2                  imshow                plot3                 union                 
det                   imtophat              plotmatrix            unique                
detectFASTFeatures    ind2sub               plotyy                uniquetol             
detectHarrisFeatures  inf                   plus                  unwrap                
detrend               inpolygon             polar                 uplus                 
diag                  int16                 poly                  var                   
diff                  int2str               polyder               vertcat               
discretize            int32                 polyfit               vissuite              
disp                  int64                 polyval               volumebounds          
display               int8                  polyvalm              voronoi               
divergence            interp1               pow2                  waterfall             
dot                   interp2               power                 xcorr                 
double                interp3               prod                  xor                   
edge                  interpn               psi                   ycbcr2rgb             
eig                   interpstreamspeed     qmr                   zeros                 
end                   intersect             qr                    
eps                   inv                   quiver                

Static methods:

colon                 rand                  randperm              
freqspace             randi                 speye                 
loadobj               randn