www.gusucode.com > rtwdemos 工具箱matlab源码程序 > rtwdemos/OptimizingControlFlow.m

    %% Optimizing Control Flow by Conbiming and Collapsing IF/SWITCH
% This example shows how the control flow (IF/SWITCH) can be optimized 
% through conbiming and collapsing in the generated code.

%   Copyright 2010-2014 The MathWorks, Inc.

%% Overview
% The IF/SWITCH constructs in the generated code represent a variety of modeling constructs such as signal
% routing, conditional logics, state transition and so on.
%
% Using data dependency analysis, this optimization combines and collapses IF/SWITCH constructs
% to reduce static code size and runtime branching
%
% The benefits of optimizing the generated code are:
%
% * Reducing the ROM and RAM consumption.
% * Improving the execution speed.


%% Review The Switch Blocks and Condition Signal
% Consider the model <matlab:rtwdemo_controlflow_opt rtwdemo_controlflow_opt>.
% In this model, there are three Switch blocks which can be combined and collapsed
% into a single IF.
model = 'rtwdemo_controlflow_opt';
open_system(model);

%% Generate Code Without This Optimization
% 
% First, generate code for this model without the optimization (preserving the IF constructs) 
% Create a temporary folder (in your system's temporary folder) for the
% build and inspection process.
currentDir = pwd;
[tempDir,cgDir] = rtwdemodir();

%%
% Build the model using Embedded Coder.
rtwbuild(model)

%%
% A portion of |rtwdemo_controlflow_opt.c| is listed below.
cfile = fullfile(cgDir,'rtwdemo_controlflow_opt_ert_rtw','rtwdemo_controlflow_opt.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%% Enable This Optimization
% # Open the Configuration Parameters dialog box.  
% # In the dialog, under *Code generation*, select *Code Style*,
% # and unselect *Preserve condition expression in if statement.
%
% Alternatively, you may use the command-line API to disable the optimization:
set_param(model, 'PreserveIfCondition', 'off');

%% Generate Code With This Optimization
% In the model, with the condition signal not side-effected by the dataflow, the IF constructs
% from the Switch block can be combined, which is subsequently collapsed to eliminate identical
% branches
%
% Therefore, the three Switch blocks are optimized into a single IF
%

%%
% Build the model using Embedded Coder.
rtwbuild(model)

%%
% A portion of |rtwdemo_controlflow_opt.c| is listed below.  Observe the optimized code.
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%%
% Close the model and cleanup.
bdclose(model)
rtwdemoclean;
cd(currentDir); 
rmdir(tempDir,'s');

displayEndOfDemoMessage(mfilename)