change operators position increase computational cost
1 ビュー (過去 30 日間)
I noticed a strange (to me) behavior in my code. I'm solving a system of ODEs using ODE15s. The following term 'prefac' is calculated many times, and I noticed that, if I used the first equation, the calculation is about half of the time faster than using the second equation (~450s VS. ~870s). The only difference is that the term ./T_c is moved from the end of the equation to the beginning. If, during the simulation, I display the difference between the two, the maximum I get is 8e-22. I used 'prefac' to calculate terms in the order of magnitude of 1e-3, and in fact the solution does not change, only the computational cost increase.
prefac = (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823) ./ (T_c);
prefac = (1 ./ (T_c)) .* (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823);
do you have some explanation for it?
Walter Roberson 2011 年 6 月 25 日
You would probably get even better performance with
5.21e-1 .* Mmix_c ./ param.R ./ T_c .* ((T_c./139.681).^1.823) .* (1-s_c) .* (param.eps_c(end,:,:) ./ param.tau_c(end,:,:)) ;
That is, do your commutative operation on scalar constants first in the expression, and then do your operations on matrices. There is no point in dividing each element of the matrix result by T_c if the matrix is also being multiplied by a scalar: instead "fold" the division into the scalar so just one division is done and the new scalar is being used for the necessary multiplication.