How to time a sketch for efficiency of coding

I was looking to be able to tell if doing a for loop (10 iterations) was more efficient than brute force 10 digitalWrite commands to turn on/off the LEDs.
The line of code is:

digitalWrite( pinArray[ loadLed ] , cML[count_cML][loadLed] );

Where loadLed is changed by the loop or hardcoded in the brute force method.
I figured capturing the value of millis() before and after either method would give me the elapsed time.
Doing it both ways yielded a difference of 0. Do both methods actually happen so fast that millis() didn't change at all?
Both before and after were declared to be unsigned long variables to properly capture the value of millis().

Thanks in advance for any insight into doing the timing better will be greatly appreciated.

You could always use micros() and see if it still takes no time at all.

a7

More efficient is addressing GPIO pins without digitalWrite, and even more efficient is parallel access to ports.

Why?

I ask because with a one byte index variable (the for loop counter) the grand total overhead is 1 + 1*10 + 2*10 = 31 clock cycles. That comes out to 1.9375 µs. Which is at least one order of magnitude smaller than a single digitalWrite call.

In other words, I suspect you are wasting your time and mental capacity on something that is so very irrelevant.

1 Like

@Delta_G
Examining the compiler output is quite a bit above my skill level, but what you state makes sense if the compiler is any good at doing its job.

@alto777
Learned a new system function today. micros() did show a difference. The loop process took about 24 micros() units longer than the brute force process. So, in this sketch, brute beats loop for speed, but the loop is much easier to deal with.

@DrDiettrich
I would need you to explain how "addressing GPIO pins without digitalWrite, and even more efficient is parallel access to ports" is done. Can you point me to an example?

@Coding_Badly
Why? Just because.
I was curious and tried to learn something.
Being retired, I have lots of time to waste on such irrelevant things that intrigue me.

1 Like

@Delta_G
Thanks for the link. First glance on it appears that several of my next few afternoons will be spent trying to wrap my mind around this concept. Ain't learning fun.

1 Like

In case you're interested in learning something that is likely to also be a good use of your time and very nicely overlaps with all-things-Arduino... Finite State Machine.

Bear in mind, timing a section of code using micros or millis can be difficult to get correct. With a difference as high as 24 µs you could also be accidentally including the timer 0 interrupt handler.

1 Like

Another option is to busy-loop for millis to increment (wait for the next interrupt to fire).

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.