Go Down

Topic: Why is there a delay at the end of void Loop? (Read 4 times) previous topic - next topic

JBMetal

I hope this is the right to place to ask this ..

I was testing the speed of pin toggling and discovered that relying on void loop{} is actually slower than placing a 'goto back to start' to repeat the loop.
Here are the two versions:
Code: [Select]


#define L_PINDEF 0  // digital latch pin #8 (portb)
#define LATCH_ON() PORTB |= _BV(L_PINDEF)
#define LATCH_OFF() PORTB &= ~_BV(L_PINDEF)

void loop() {
  start:
  LATCH_ON();
  LATCH_OFF();
  LATCH_ON();
  LATCH_OFF();
goto start;
} // with goto

void loop() {
  LATCH_ON();
  LATCH_OFF();
  LATCH_ON();
  LATCH_OFF();
} // without




The scope says 880Khz to repeat cycle without goto:



And 1.6MHz to repeat cycle with goto:



Any ideas why this may be?   :~

Onions

In hardware->arduino->cores->arduino lies the 'main.cpp' file:

Code: [Select]
#define ARDUINO_MAIN
#include <Arduino.h>

int main(void)
{
init();

setup();
   
for (;;)
loop();
       
return 0;
}



So after the function 'void loop()' has finished, the control returns to the above file. The above file then calls void loop() again, and so on. This takes time.

Onions.
My website: http://www.harryrabbit.co.uk/electronics/home.html Up and running now! (Feel free to look round!) :D

JBMetal

Nothing wrong with adding a goto then to squueze out an extra +- 500 ns?  :D

PaulS

Quote
Nothing wrong with adding a goto then to squueze out an extra +- 500 ns?

Yes, there is. There is no reason you can't use a more readable structure:
Code: [Select]
void loop() {
  while(1)
  {
    LATCH_ON();
    LATCH_OFF();
    LATCH_ON();
    LATCH_OFF();
  }
} // without goto

JBMetal

@KE7GKP: Doing some research into POV so I am looking for every extra Hz I can find.

While is defintely prettier   :)

Although finding a label is easier in long code than tracing a {} pair? After several copy,paste procedures my indentation quickly goes to the dogs  :(

Go Up