View Single Post
Old 07-24-2009, 09:48 AM   #14
liteon
Human being with feelings
 
liteon's Avatar
 
Join Date: Apr 2008
Posts: 510
Default code optimizations

this syntax is troublesome for the given function due to the 'pow' operator:
Code:
y=7*x^4+5*x^3-3*x^2+2*x-1;
this is better:
Code:
y=7*x*x*x*x+5*x*x*x-3*x*x+2*x-1;
even better:
Code:
y=x;
y*=7;
y+=5;
y*=x;
y-=3;
y*=x;
y+=2;
y*=x;
y-=1;
best:
Code:
y=x*(x*(x*(7*x+5)-3)+2)-1;
-----------------------------------------------
however it is slightly faster to execute:
Code:
x=6.28;
x*=2;
x|=0;
x%=3;
over:
Code:
x=6.28;
x=((2*x)|0)%3;
-----------------------------------------------
if there are more variables and recursion:
Code:
@sample
y=y0+k*spl0;
y0=spl0-k*y;
spl0=y;
could be optimized to:
Code:
y0=spl0-k*(y=y0+k*spl0);
spl0=y;
-----------------------------------------------
loops:

loop() - 73% cpu
Code:
i=0;
loop(100,
mem[i]=exp(i);
i+1;
);
while() - 76% cpu
Code:
i=0;
while(
mem[i]=exp(i);
i+=1;
i<100; //<- inlined cmp - eventual cause for 76%
);
-----------------------------------------------
min() / max() or inline cmp:

Code:
x=0.9;
//this call
x<1?x=1;
//is slower than
x=max(x,1);
-----------------------------------------------
abs() and sign() are both quite fast:
correction here:
Code:
//alternative to abs()
x=-0.5;
x*=sign(x);
//700 iterations, x=-0.5, x=abs(x) -> 82.6% cpu, x*=sign(x) -> 84.5% cpu
//700 iterations, x=0.5, x=abs(x) -> 80.1% cpu, x*=sign(x) -> 76.5% cpu
//--
//if input values are mostly with negative sign use abs(x)

---
lubomir

Last edited by liteon; 03-28-2011 at 10:40 PM.
liteon is offline   Reply With Quote