Matlab 应用GPU加速

article/2025/8/27 16:24:08

由于GPU近几年地迅速发展,GPU在多线程计算等方面逐渐超越CPU成为计算的主力军。而Matlab是常用的数学应用软件,现在讲解一下如何在Matlab中使用GPU加速计算

文章目录

    • 0. 必要条件
    • 1.给GPU传输数据
      • 1.1 CPU的数据复制到GPU
      • 1.2 直接在GPU上设置数据:
    • 2.数据在GPU上运算
    • 3.GPU数据回传
    • 4.使用技巧
      • 4.1 如果没有并行计算不建议使用GPU
      • 4.2 如果没有Nvidia显卡或者显卡驱动
      • 4.3 双精度尽量转换为单精度
    • 附录

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 如果没有并行计算不建议使用GPU

index = 0;
index = gpuArray(index);
for i = 1 : 10000ticfor j = 1 : 100000index = index + 1;endtoc
end
disp(index)

通过上边程序第二行程序就可以在GPU上运行,注释掉就会在CPU上运行。在我的电脑上运行时间如下表所示。

设备CPUGPU
时间0.00010 s1.973017 s

由此可以看出,单个线程运行程序还是建议在CPU上运行,CPU的主频还是高一点,GPU主要是支持多个线程同时运行。

4.2 如果没有Nvidia显卡或者显卡驱动

如果没有Nvidia显卡或者显卡驱动,会显示下边的提示。

这里写图片描述

4.3 双精度尽量转换为单精度

在条件允许的情况下,尽量将计算过程中双精度转换为单精度。因为在GPU中单精度的计算速度明显优于双精度,在时间上会有很大的缩减。
附:单精度与上精度区别

数据类型大小(字节)取值范围保留有效位数
单精度4个字节(32位)3.4E-38~3.4E+387位
双精度8个字节(64位)1.7E-308~1.7E+30816位

参考:
Measuring GPU Performance - MATLAB & Simulink Example - MathWorks 中国

MATLAB上的GPU加速计算——学习笔记 - CSDN博客

附录

>> 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  

http://chatgpt.dhexx.cn/article/nVXvwVh0.shtml

相关文章

tensorflow的GPU加速计算

参考 tensorflow的GPU加速计算 - 云社区 - 腾讯云 一、概述 tensorflow程序可以通过tf.device函数来指定运行每一个操作的设备,这个设备可以是本地的CPU或者GPU,也可以是某一台远程的服务器。tensorflow会给每一个可用的设备一个名称,tf.…

Pytorch使用GPU加速

1. 可以在cmd窗口输入nvidia-smi命令来确认自己的显卡是否有CUDA。 没有的话,需要安装。(搜CUDA官网按照步骤来) 2. 然后安装pythorch。 必须安装的有torch和torchvision两个包, !注意不要直接在Pycharm中自动下…

一文读懂:GPU加速是什么?

众所周知,网页不仅应该被快速加载,同时还应该流畅运行,比如快速响应的交互,如丝般顺滑的动画…… 一. GPU加速能做什么? 首先我们要了解什么是16ms优化 大多数设备的刷新频率是60次/秒,(1000…

MATLAB使用GPU加速计算

先上结论 1、对于特征值运算eig()函数来说,GPU的加速效果是很明显的 2、如果要求精度不高,采用单精度计算,加速效果更加明显 首先查看自己的电脑是不是支持GPU计算 在matlab的终端中输入: gpuDevice()可以看出我电脑的显卡为N…

了解GPU加速计算

1、什么是GPU加速计算 GPU,又称显示核心、视觉处理器、显示芯片,是一种专门在个人电脑、工作站、游戏机和一些移动设备(如平板电脑、智能手机等)上图像运算工作的微处理器,与CPU类似,只不过GPU是专为执行复…

Python GPU加速

Numba:高性能计算的高生产率 在这篇文章中,笔者将向你介绍一个来自Anaconda的Python编译器Numba,它可以在CUDA-capable GPU或多核cpu上编译Python代码。Python通常不是一种编译语言,你可能想知道为什么要使用Python编译器。答案当然是&#x…

关于TensorFlow使用GPU加速

我们在安装tensorflow-gpu后,其运行时我们可以选定使用gpu来进行加速训练,这无疑会帮助我们加快训练脚步。 (注意:当我们的tensorflow-gpu安装后,其默认会使用gpu来训练) 之前博主已经为自己的python环境安装了tensorf…

GPU加速原理

原文:https://blog.csdn.net/weiweigfkd/article/details/23051255 GPU加速技术&原理介绍 1、GPU&CPU GPU英文全称Graphic Processing Unit,中文翻译为“图形处理器”。与CPU不同,GPU是专门为处理图形任务而产生的芯片。从这个任务定…

让GPU跑的更快

作为一个cuda爱好者 一定要好好看看 不再让CPU和总线拖后腿:Exafunction让GPU跑的更快!确实只用cpu会卡的一比... 在云服务中使用 GPU 是获得低延迟深度学习推理服务最经济的方式。使用 GPU 的主要瓶颈之一是通过 PCIe 总线在 CPU 和 GPU 内存之间复制…

什么是GPU 加速?

1、什么是GPU加速计算 GPU,又称显示核心、视觉处理器、显示芯片,是一种专门在个人电脑、工作站、游戏机和一些移动设备(如平板电脑、智能手机等)上图像运算工作的微处理器,与CPU类似,只不过GPU是专为执行复…

什么是GPU加速

1、什么是GPU加速计算 GPU,又称显示核心、视觉处理器、显示芯片,是一种专门在个人电脑、工作站、游戏机和一些移动设备(如平板电脑、智能手机等)上图像运算工作的微处理器,与CPU类似,只不过GPU是专为执行复…

GPU加速原理技术介绍

GPU加速技术&原理介绍 1、GPU&CPU GPU英文全称Graphic Processing Unit,中文翻译为“图形处理器”。与CPU不同,GPU是专门为处理图形任务而产生的芯片。从这个任务定位上面来说,不仅仅在计算机的显卡上面,在手机、游戏机等等各种有多媒体处理需求的地方都可以见到…

GPU加速原理浅析及代码实现

GPU加速原理浅析及代码实现 一、CUDA简介二、GPU架构特点三、CUDA线程模型四、CUDA内存模型五、CUDA编程规范**第一个要掌握的编程要点**:**我们怎么写一个能在GPU跑的程序或函数呢?****第二个要掌握的编程要点**:**CPU和GPU间的数据传输怎么…

1129-

标题1-行情概览 标题2-行情图片 标题3-重点分析 WTA原油七点开盘高开高走,导致国内原油跌停板上高开高走,下午一点半不知道什么原因又低开。铁矿收一根4.7%的大阳线。贵金属高开高走

连接mysql报错 errorCode 1129, state HY000, Host ‘xxx‘ is blocked because of many connection errors

springcloud项目启动连接mysql过程中报错. 报错关键信息如下: java.sql.SQLException: null, message from server: "Host 192.168.56.1 is blocked because of many connection errors; unblock with mysqladmin flush-hosts" 错误原因: mysql设定了单个客户端…

Navicat连接MySQL 报错 1129

启动本地项目时,由于nacos设置的数据库账号密码未将本地改为线上,导致数据库连接多次而报错,另外navicat进到该IP的线上库也报错1129,报错信息 Host’123.45.678.99’ is blocked because of many connection errors; unblock wit…

ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1129)

在使用 requests 爬网站时报错: ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1129)urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(hostmooc1-1.chaoxing.com, port443): Max retries exceeded with url: /work/ .......requests.ex…

【dfs爆搜】poj 1129 Channel Allocation

1129 -- Channel Allocation (poj.org) 题意: 大致的题意就是给你一张图,给这张图染色,最多能染多少种颜色 思路: 首先要构造状态图,构造完状态图之后对其进行搜索(注意是先有图再有的dfs,而…