%% Minimize Global Data Access
% Generate optimized code that reads from and writes to global variables less frequently.
%% Example Model
% In the model matlab:rtwdemo_optimize_global, five signals feed into a Multiport Switch block.

model = 'rtwdemo_optimize_global';
load_system('rtwdemo_optimize_global')

%
%
%% Generate Code without Optimization
% In the Configuration Parameters dialog box, verify that the Signal storage reuse parameter is selected.
% In the Configuration Parameters dialog box, for the Optimize global data access parameter, select None or enter the following command in the MATLAB Command Window:

set_param('rtwdemo_optimize_global','GlobalVariableUsage','None');

%
% In your system's temporary folder, create a folder for the build and inspection process.

currentDir = pwd;
[~,cgDir] = rtwdemodir();

%
% Build the model.

rtwbuild(model);

%
% View the generated code without the optimization. Here is a portion of rtwdemo_optimize_global.c.

cfile = fullfile(cgDir,'rtwdemo_optimize_global_ert_rtw',...
    'rtwdemo_optimize_global.c');
rtwdemodbtype(cfile,'/* Model step','/* Model initialize',1, 0);

% In the Static Code Metrics Report, examine the Global Variables section.
% In the Code Generation Report window, select Static Code Metrics Report.
% Scroll down to the Global Variables section.
% Select the [+] sign before each variable to expand it.
%
% The total number of reads and writes for global variables is 5.
%
%% Enable Optimization and Generate Code
% In the Configuration Parameters dialog box, for the Optimize global data access parameter, select Minimize global data access or enter the following command in the MATLAB Command Window:

set_param('rtwdemo_optimize_global',...
    'GlobalVariableUsage','Minimize global data access');

%
% Build the model.

rtwbuild(model);

%
% View the generated code with the optimization. Here is a portion of rtwdemo_optimize_global.c.

cfile = fullfile(cgDir,'rtwdemo_optimize_global_ert_rtw',...
    'rtwdemo_optimize_global.c');
rtwdemodbtype(cfile,'/* Model step','/* Model initialize',1, 0);

% In rtwdemo_optimize_global.c, the code assigns a constant value to the local variable tmp_Out1 in each case statement. The last statement in the code copies the value of tmp_Out1 to the global variable rtY.Out1. Fewer global variable references result in fewer instructions and improved execution speed.
% In the Static Code Metrics Report, examine the Global Variables section. As a result of minimizing global data accesses, the total number of reads and writes for global variables has decreased from 5 to 2.
%
%
% Close the code generation report.

rtwdemoclean;
cd(currentDir)

% Copyright 2012 The MathWorks, Inc.