I did some experimentation on this, and it turns out that making the constants persistent actually slows down the code by a factor of 3-5 times. Defining them using a separate function (to separate them from the computational part of the code) did not slow things down.
Best Practice for Defining Large Constant Array in Function (Must Code-generate)
조회 수: 19 (최근 30일)
이전 댓글 표시
I have a function that uses a largish array of constant Legendre polynomial coefficients. I'm curious, from a performance standpoint, of the best way to define these constants in a MATLAB Function. The simplest approach is to define them directly:
function y = foo(x)
%#codegen
coeff = [1,2,3,3;...
2,34,45,5;...
45,565,56754,43;
.
. % Many lines of coeff.
.
.];
y = someFunction(x,coeff);
end
I could make coeff persistent as follows, but am not sure if there is any performance benefit of doing this:
function y = foo(x)
%#codegen
persistent coeff
if isempty(coeff)
coeff = [1,2,3,3;...
2,34,45,5;...
45,565,56754,43;
.
. % Many lines of coeff.
.
.];
end
y = someFunction(x,coeff);
end
I'm curious about the consesus on best practice in this circumstance, I need the resulting function to code-generate in a Simulink MATLAB function.
댓글 수: 5
Jeff Miller
2020년 4월 11일
Thanks for testing it. That's very disappointing performance in the case of the ReallySlow version of the function. Maybe it would be faster as a handle class.
But if the class doesn't speed things up and the coefficients are not used anywhere else, it's pretty hard to see any reason to prefer it over the simpler plain function approach
답변 (1개)
Sean de Wolski
2020년 4월 10일
편집: Sean de Wolski
2020년 4월 10일
Look at using System Objects and the MATLAB System block in Simulink. These are optimized for streaming workflows and code generation.
댓글 수: 2
Sean de Wolski
2020년 4월 16일
System objects are fit well for the dual use case that you point out. I.e. use in MATLAB or direct reuse in Simulink with the MATLAB System Block.
I don't understand all of the internals, but they're supposed to be efficient in how the JIT or generated code manage things to make the step() method as fast as possible for real-time systems. Hence why the DSP System Toolbox has many of these objects all geared for code generation. If your states aren't changing, they may be of little value. In my experience, much of the OO overhead was improved in >=R2015b with the new MATLAB execution engine.
Check out this video https://www.mathworks.com/videos/accelerate-image-compression-algorithm-77688.html
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!