how to optimize const (sub-) expressions?
ManAtWork
Posts: 2,176
When I pass parameters to pasm functions I often need scaling factors that are composed out of multiple sub-factors. For example
#define adcLsbPerV (65536.0 / 3.3) // ADC resolution LSBs per volt #define sensorGain 0.1 // current sensor output 100mV/A void SetNomCurr (float df, float qf) { ctrl.currNomD= df * (adcLsbPerV * sensorGain); }I thought (whishful thinking) the compiler would recognize that the expression in the brackets is constant and can be pre-calculated at compile time. But it generates all code literally, instead, producing one division and two multiplications. Since floating point operations are expensive I'd like to avoid that and try to get one multiplication, only. Of course, I could do the pre-calculation myself and write
ctrl.currNomD= df * 1985.939393;But that looks ugly and is not very maintenance friendly. If I took a different sensor I had to search and replace every occurance of the constant. I also tried
const float f = adcLsbPerV * sensorGain; ctrl.currNomD= df * f;But that still produces runtime code for one float div and two muls. If I use "static const" I get strange compiler errors pointing at random different locations in my code the have compiled without errors, before. I remember there is a "constexp" qualifier in C++. In Spin1 there also was "const()" to tell the compiler that a (sub-) expression can be calculated at compile time. Is there a trick I can use in Fastspin C?
Comments
Thanks for your support!