Knowing that the min macro is ((a)<(b)?(a):(b)) shouldn't the second version be even a little faster when x is not greater than maxValue because it doesn't assign a new value to x ?
And what about the constrain macro ?
This:
x = constrain(x, minValue, maxValue);
Or this:
if (x < minValue) x = minValue;
else if (x > maxValue) x = maxValue;
x = min(x, maxValue);
x = volatile int 50, maxValue = volatile int 51 : 1.3 us
x = volatile int 50, maxValue = volatile int 49 : 1.2 us (code size is about 6 bytes longer)
x = volatile int 50, maxValue = const int 51 : 1.1 us
x = volatile int 50, maxValue = const int 49 : 0.88 us (code size is about of 9 bytes longer)
if (x > maxValue) x = maxValue;
x = volatile int 50, maxValue = volatile int 51 : 0.7 us
x = volatile int 50, maxValue = volatile int 49 : 0.7 us
x = volatile int 50, maxValue = const int 51 : 0.5 us
x = volatile int 50, maxValue = const int 49 : 0.5 us
When using two variables that are located somewhere in memory, the second version (if...) is almost twice as fast. The difference is less big when a constant value is used for the 'maxValue'.
I have a large increase of the code size with the min() macro. That is because I use many code lines that are all the same, to improve the timing measurement. The extra bytes are per code line. The compiler optimizes those many code lines in a different way.
x = min(x, maxValue);
x = volatile int 50, maxValue = volatile int 51 : 1.3 us
x = volatile int 50, maxValue = volatile int 49 : 1.2 us (code size is about 6 bytes longer)
x = volatile int 50, maxValue = const int 51 : 1.1 us
x = volatile int 50, maxValue = const int 49 : 0.88 us (code size is about of 9 bytes longer)
if (x > maxValue) x = maxValue;
x = volatile int 50, maxValue = volatile int 51 : 0.7 us
x = volatile int 50, maxValue = volatile int 49 : 0.7 us
x = volatile int 50, maxValue = const int 51 : 0.5 us
x = volatile int 50, maxValue = const int 49 : 0.5 us
When using two variables that are located somewhere in memory, the second version (if...) is almost twice as fast. The difference is less big when a constant value is used for the 'maxValue'.
I have a large increase of the code size with the min() macro. That is because I use many code lines that are all the same, to improve the timing measurement. The extra bytes are per code line. The compiler optimizes those many code lines in a different way.
Thank you very much, I really appreciate your help
So to summarize it: Using the second version is faster (even if it's just 0.1 uS) and even uses less bytes (if I got the second part right)
Yes, but it is very arbitrary. Normally the 'x' value is already in a register, and the compiler optimization uses that. So in the end the difference might be less.