Let's say I have this code below:
int led = 13;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
ledChange(HIGH);
delay(1000);
ledChange(LOW);
delay(1000);
}
void ledChange(int pinState) {
digitalWrite(led, pinState);
}
Does moving digitalWrite(led, pinState);
to its own function affect processing time?
Of course, performance doesn't matter with a single LED, but it could matter when every clock cycle counts (high sampling rates, lots of math in loops, etc.).
Yes, you are wasting a teensy amount of clock cycles. When you write ledChange(LOW)
, it is compiled to a CALL type instruction (which tells the program counter register to jump to the location of the method).
So, this will basically compile to:
LOW
in some register or the stackledChange()
led
from memory, and put it along with LOW
somewheredigitalWrite()
digitalWrite()
Note that a CALL
jump involves a lot of messing with the stack, and takes a lot longer than a regular JMP
instruction.
On the other hand, doing just digitalWrite(led,LOW)
will do:
led
,LOW
from somewhere on the memory and put them somewhere accessibleditigalWrite()
digitalWrite()
I'm not entirely sure how arguments are passed in the corresponding compiled code, it's probably a part of the call. Also note that compilers vary, and some are smarter than others.
You can see that your encapsulation of the function made the program take up more clock cycles every time you while running it. However, this isn't really worth optimizing; I don't see much capacity in such encapsulation to slow down the Arduino. Besides, like I mentioned, some compilers optimize such things.
This has nothing to do with the function being a void
. If it was an int
function, it would be ever-so-slightly slower since storing the int before return involves a MV
or stack operation (forgot which).
A function being defined as void simply informs the compiler / optimizer that there is no return value expected from the function.
There will thus be no code generated for saving or manipulating any return value.
This is not Arduino specific, it is a generic C behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With