Help storing max value efficiently

I'm trying to store the max value of a 9Dof IMU (BNO055) each time it is triggered and I'm wondering if there is more efficient way than the following :-

 if (acc.x() > max_accelX){

max_accelX = acc.x;

I have 12 of these to do (max +ve and max -ve) and I just don't fancy the look of 12 if statements if there is a nice way of writing it.



I’d like to see one.

You must do the test, you must do the assignment.

If the values and maximums were in arrays, it could be coded as a loop and look prettier, maybe, and be fewer lines of code.

The loop might be insignificantly slightly faster.

For twelve that weren’t convenient in an array, just write the lines of code.

Oh, a function might make it look pretty, too. More lines of code, slower, less slightly.

It just comes down to the number of them. Again for twelve I would just you know.

HTH and looking forward to the clever thing I missed.


You can just write

max_accelX = max(acc.x, max_accelX);

I can’t say that’s the function I had in mind. :expressionless:


Nice one PaulRB! Much prettier :wink:

What function do you have in mind. Just asking

One a person could write for himself, using call by reference I was thinking.

It would do what max() does just a bit differently and unique. Might have even made me remember max(), I see it all over the place…

Which is like most of my code, I get more whatever at all it is I do out of this stuff writing my own things as opposed to using this or that library, &c.

But forgetting about or eschewing the use of max() shouldn’t be part of that.

So file this under I am reminded of something every day.



Prettier ways, perhaps.
More efficient ways, I don't think so. Like alto77 said, you always have to do the comparison, and you need to do the new store if appropriate. Looping though an array might gain slightly by minimizing address manipulation (increment an index register instead of fetching from a new absolute location), and lose slightly doing the looping and manipulating the index, but it's likely to be very close.

#define update_max(current_max, new_value) if (new_value > current_max) current_max = new_value

update_max(max_accelX, acc.x);
update_max(max_accelY, acc.Y);
update_max(max_accelZ, acc.Z);