call function - slow

12 Ansichten (letzte 30 Tage)
Alessandro D
Alessandro D am 18 Sep. 2018
Beantwortet: Sambit Senapati am 21 Sep. 2018
Dear users, I am struggling with optimizing the code for a project of mine and I am following the suggested practice of breaking my code in small parts with separate functions. However when I do this I get a significant loss in execution speed. Please consider the following two examples:
A)
function y = fun1(a,params)
%params is structure with several variables
b = a*2;
y = b+1;
end %end fun1
compared to
B)
function y = fun1(a,params)
%params is structure with several variables
b = fun2(a,params);
y = b+1;
end %end fun1
function b = fun2(a,params)
b = a*2;
end %end fun2
(B) is easier to maintain but for my application is 20/30% slower. (Of course the example above is a toy example). One reason could be that I have to pass to fun2 "params" which is a big structure. But using globals would be even worse, are there any other (fast) ways? Thanks!
  3 Kommentare
Guillaume
Guillaume am 18 Sep. 2018
Bearbeitet: Guillaume am 18 Sep. 2018
If params is not modified by fun2, then passing it to fun2 is just a pointer copy (8 bytes) regardless of the size of params, and so will not cause any noticeable slowdown. If params does get modified in fun2, then you will incur a copy of the whole content which could take some time if it's big.
I think you need to get into more details of what actually happens in your fun2.
Alessandro D
Alessandro D am 18 Sep. 2018
Dear guys, thanks for your answers. These are some more detail. In fun2 I need to unpack the structure params. But params itself is not modified
function y = fun1(a,params)
%params is structure with several variables
b = fun2(a,params);
y = b+1;
end %end fun1
function b = fun2(a,params)
agrid = params.agrid;
zgrid = params.zgrid;
na = params.na;
nz = params.nz;
uf = params.uf;
tranZ = params.tranZ;
amin = min(agrid); amax = max(agrid);
%Do some operations with agrid, zgrid etc.
b = a*2 + agrid.^2;
end %end fun2

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Sambit Senapati
Sambit Senapati am 21 Sep. 2018
Please go through the this link which describes about performance of different types of function calls. This may help you to figure out why your code is slow.

Weitere Antworten (0)

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by