Matlab creates a local copy every time I use/modify a global variable
Show older comments
Dear all,
I've noticed that Matlab spends a lot of time executing quite simple code with about linear complexity. I've generated a C code of this function using Embedded Matlab Compiler as follows:
rtwcfg = emlcoder.RTWConfig;
rtwcfg.CustomSource = 'main.c';
% Warning: Matlab uses a lot of (6Gb) memory to generate C code.
emlc -T rtw:exe -s rtwcfg -global {'tree', tree, 'tree_size', tree_size,'test_cycle', test_cycle, 'max_nodes', max_nodes} test7_SOC_SARSA_BSP1_UDDS_cycle_T_embedded;
The executable runs even worse the original Matlab programm. In the C code I see that every time the global variable "tree" is used Matlab copies it into another local variable. For example:
if (rand() > epsilon)
[~, a] = max(tree(s).Q);
else
%a = randi(nactions, 1);
end
is transformed to:
eml_a = 0.0;
eml_r = m_refp1_genrandu(twister_state);
if(eml_r >= 0.0) {
m_cast(tree, eml_hoistedExpr);
m_b_max(eml_hoistedExpr[(int32_T)eml_s - 1].Q, &eml_r, &eml_a);
} else {
/* a = randi(nactions, 1); */
}
Here is the code of the m_cast() function:
void m_cast(const struct sDbrZRlzGvadVfPbni0fyYH eml_x[50001], struct
sDbrZRlzGvadVfPbni0fyYH eml_y[50001])
{
int32_T eml_j;
for(eml_j = 0; eml_j < 50001; eml_j++) {
eml_y[eml_j] = eml_x[eml_j];
}
}
as you may observe it copies first input arg to the second one.
Why does Matlab create these copies? Is it possible to avoid them? Thank you very much in advance for any help and your time,
Regards, Dmitry
Answers (1)
Kevin
on 25 Mar 2011
0 votes
The cast might be caused by a mismatch in the number of dimensions in the indexing expression tree(s). What is size(tree)? If it is [1 50001] then you may be able to eliminate the cast by writing tree(1,s) rather than tree(s).
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!