Why is code faster when broken across multiple lines?
Afficher commentaires plus anciens
Trying to speed up some code, so I used Wolfram Alpha to find an analytical form of what I was previously computing as a numerical integral. Curiously, the integral goes way faster when I break the code up. I have something of a reputation at work for knowing how to speed up other people's Matlab code, so I'd like to understand why i0 takes so much longer to compute than i (and l1-l5):
i=indefiniteIntegral(1/3,100*rand(1e6,2)); % <-- run this in the profiler
function i = indefiniteIntegral(a,x)
E1 = a*sqrt(x.^2+1);
E2 = 2*a-1;
E3 = sqrt(E2);
E4 = (a-1)*x;
l1 = -a^2*log(E1+E4+E3);
l2 = -a^2*log(E1-E4+E3);
l3 = a^2*log(-2*a*x+a*E3-E3+x);
l4 = a^2*log(2*a*x+a*E3-E3-x);
l4b = -2*a^2*atanh((E3*x)/(a-1));
l5 = 2*E3*E1+2*E3*a*x-2*E3*x;
i=.5*E2^(-3/2)*(l1+l2+l3+l4+l4b+l5);
i0=.5*E2^(-3/2)*(-a^2*log(E1+E4+E3)-a^2*log(E1-E4+E3)+a^2*log(-2*a*x+a*E3-E3+x)+a^2*log(2*a*x+a*E3-E3- x)-2*a^2*atanh((E3*x)/(a-1))+2*E3*E1+2*E3*a*x-2*E3*x);
% assertEqual(i,i0,1e-4); % My own function for checking equality within a tolerance, and i is equal to i0 in this case
% Reference: http://www.wolframalpha.com/input/?i=integrate+1%2F%281-a*%281-x%2F%28sqrt%281%2Bx%5E2%29%29%29
Is this an artifact of profiling or something? My typical usage, in case it matters, is that I'm given a bunch of values in x, and I run:
i = diff(abs(indefiniteIntegral(a,[-x,0])),[],2);
All the math seems to work, I mean I get the correct values compared to numerical integration, I just want to understand why the code runs faster when I split it up (which I did only for readability at first).
Réponse acceptée
Plus de réponses (1)
Sean de Wolski
le 5 Nov 2014
1 vote
The JIT accelerator is sometimes able to better optimize code that has been split into pieces.
2 commentaires
Steve
le 5 Nov 2014
Sean de Wolski
le 5 Nov 2014
It's kind of one of those: "Your mileage will vary" things.
Catégories
En savoir plus sur Historical Contests dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!