algorithm - Optimizing C code, Horner's polynomial evaluation -
i'm trying learn how optimize code (i'm learning c), , in 1 of books there's problem optimizing horner's method evaluation polynomials. i'm little lost on how approach problem. i'm not great @ recognizing needs optimizing.
any advice on how make function run faster appreciated.
thanks
double polyh(double a[], double x, int degree) { long int i; double result = a[degree]; (i = degree-1; >= 0; i--) result = a[i] + x*result; return result; }
you need profile code test whether proposed optimizations help. example, may case declaring i
long int
rather int
slows function on machine, on other hand may make no difference on machine might make difference on others, etc. anyway, there's no reason declare i
long int
when degree
int
, changing won't hurt. (but still profile!)
horner's rule supposedly optimal in terms of number of multiplies , adds required evaluate polynomial, don't see can it. 1 thing might (profile!) changing test i>=0
i!=0
. of course, loop doesn't run enough times, you'll have add line below loop take care of final case.
alternatively use do { ... } while (--i)
construct. (or do { ... } while (i--)
? figure out.)
you might not need i
, using degree
instead not save observable amount of time , make code harder debug, it's not worth it.
another thing might (i doubt it, profile!) breaking arithmetic expression inside loop , playing around order, like
for (...) { result *= x; result += a[i]; }
which may reduce need temporary variables/registers. try out.
Comments
Post a Comment