Reputation: 81
Hy there everyone!
I'm doing good progress on my AVR for my DIY sprinkler and fish tank automatization, but I've come across a question, that bugs me.
Which if statement runs on the AVR faster?(in less clock cycles) By how much?
if(temp_sensor[0] < -20)
{
OCR1A--;
}
else if(tempout > tempset)
{
OCR1A--;
}
Or
if((temp_sensor[0] < -20) || (tempout > tempset))
{
OCR1A--;
}
On second thought, my second question is: Which one uses less space?
My conclusion: First of all, thanks everyone for your answers and comments!
The primary objective should be to write a clean code, that is easy to understand.
Upvotes: 2
Views: 1480
Reputation: 6116
Adding to unwind, you can also use it this way:
OCR1A -= (uint8_t)((temp_sensor < -20) | (tempout > tempset));
|
is bitwise OR.
This will remove the JUMP
code required for Logical OR (||
).
Upvotes: 0
Reputation: 7608
Write code for readability, not for speed. Especially in those very trivial cases where the compiler can easily figure out what is happening and optimize it.
You should avoid the 1st way because you have some duplicated code in it, which isn't ideal.
Also I must point out that unless optimized, an || or an &&, are compiled to branch instructions the same way an if statement is, so they do improve readability in the code but don't really bring any performance advantage.
Upvotes: 3
Reputation: 11597
this way
if((temp_sensor[0] < -20) || (tempout > tempset))
{
OCR1A--;
}
is better way to write these kind of conditions. it is more understandable. as to if it takes less ticks it's not really significant, unless you do it hundred of thousand of times, and in this case just check them both and see which is better
Upvotes: 0
Reputation: 399999
You could try for a (seemingly) jumpless approach:
const int8_t delta = temp_sensor < -20 || tempout > tempset;
OCR1A -= delta;
That can sometimes give shorter code. Of course it's very CPU-dependent, not sure how well the AVR likes code like this. It very well might generate a jump for the short-circuiting of the ||
operator, too. It's also totally possible for the compiler to optimize itself out of the jumps all on its own.
Upvotes: 3