将具有并行功能的 MATLAB 函数部署为独立应用程序
此示例说明如何使用 MATLAB® Compiler™ 将并行运行的蒙特卡罗仿真部署为独立应用程序。
当您将并行运行的 MATLAB® 函数部署为独立应用程序时,运行代码的集群的集群配置文件必须可供该 MATLAB 函数使用。您可以通过以下方式设置集群配置文件:
在 MATLAB 函数代码中包含集群配置文件的路径。
在将 MATLAB 函数打包为独立应用程序时,将集群配置文件作为附加文件一并包含。
在运行时将集群配置文件传递给独立应用程序。
您可以使用 setmcruserdata 函数在 MATLAB 函数内设置集群配置文件,并通过 mcruserdata 选项在运行时将该配置文件传递给独立应用程序。有关详细信息,请参阅在部署的应用程序中使用 Parallel Computing Toolbox。
在此示例中,在将 MATLAB 函数打包为独立应用程序时,集群配置文件作为附加文件一并包含。有关如何在运行时传递集群配置文件的详细信息,请参阅在运行时传递集群配置文件。
创建 MATLAB 函数
编写一个名为 mcsim 的 MATLAB 函数,用于基于美元拍卖模型运行简单的随机仿真。该函数通过蒙特卡罗方法运行多次仿真,以确定一美元纸币的市场价值。将该函数保存在名为 mcsim.m 的文件中。有关详细信息,请参阅使用 parfor 加速蒙特卡罗代码 (Parallel Computing Toolbox)。
function B = mcsim(nTrials, nPlayers, incr, dropoutRate) %% specify cluster profile mpSettingsPath = which('deployLocal.mlsettings'); setmcruserdata('ParallelProfile', mpSettingsPath); %% parfor-loop to produce nTrials samples % store the last bid from each trial in B t = zeros(1,5); for j = 1:5 tic parfor i = 1:nTrials bids = dollarAuction(nPlayers,incr,dropoutRate); B(i) = bids.Bid(end); end t(j) = toc; end parforTime = min(t); %% display results disp(['parforTime = ' num2str(parforTime)]) disp(['Average market value = ' num2str(mean(B))])
在此示例中,在将 MATLAB 函数打包为独立应用程序时,集群配置文件作为附加文件一并包含。由于打包时添加到应用程序中的所有文件都会被添加到应用程序的搜索路径,因此在上方代码中使用 which 命令将返回集群配置文件的绝对路径。然后,您可以通过 setmcruserdata 函数使用集群配置文件的路径设置集群配置文件。
使用 compiler.build.standaloneApplication 创建独立应用程序
使用 compiler.build.standaloneApplication 函数从 MATLAB 函数创建独立应用程序。
appFile = "mcsim.m"; parallelProfileFile = fullfile(pwd,'deployLocal.mlsettings'); buildResults = compiler.build.standaloneApplication(appFile,... "AdditionalFiles",parallelProfileFile,... "TreatInputsAsNumeric",'on')
buildResults =
Results with properties:
BuildType: 'standaloneApplication'
Files: {2×1 cell}
IncludedSupportPackages: {}
Options: [1×1 compiler.build.StandaloneApplicationOptions]
该函数会在当前工作目录中名为 mcsimstandaloneApplication 的文件夹中生成可执行文件。
注意:
生成的独立应用程序不是跨平台的,可执行文件类型取决于生成它时所基于的平台。
生成的独立应用程序不包括 MATLAB Runtime 或安装程序。要使用
buildResults对象创建安装程序,请使用compiler.package.installer函数。
测试独立应用程序
要在 MATLAB 中运行 mcsim,请在 MATLAB 桌面环境中导航到 mcsimstandaloneApplication 文件夹,然后根据您的操作系统执行以下命令之一:
Windows
!mcsim.exe 10000 20 0.05 0.01
Starting parallel pool (parpool) using the 'deployLocal' profile ... Connected to parallel pool with 4 workers. parforTime = 5.3772 Average market value = 5.8624
Linux
!./mcsim 10000 20 0.05 0.01
macOS
system(['./run_mcsim.sh', matlabroot, '10000','20', '0.05', '0.01']);
运行独立应用程序
在系统命令提示符下,导航到包含独立可执行文件的文件夹。
根据您的操作系统,使用以下命令之一运行 mcsim:
Windows
mcsim.exe 10000 20 0.05 0.01
Linux
使用 shell 脚本:
./run_mcsim.sh <MATLAB_RUNTIME_INSTALL_DIR> 10000 20 0.05 0.01
使用可执行文件:
./mcsim 10000 20 0.05 0.01
macOS
使用 shell 脚本:
./run_mcsim.sh <MATLAB_RUNTIME_INSTALL_DIR> 10000 20 0.05 0.01
使用可执行文件:
./mcsim.app/Contents/macOS/mcsim 10000 20 0.05 0.01
在运行时传递集群配置文件
要在运行时传递集群配置文件,请在执行应用程序时使用 mcruserdata 选项。
mcsim 10000 20 0.05 0.01 -mcruserdata ParallelProfile:'<path>\clusterProfile.mlsettings'