Hello,
I'm in the middle of porting one of my projects which I started in 2003 over to the Arduino platform. Namely, I'm modernizing the device using newer technologies. While writing native code was nice and the throughput was great, I also spent far too much time writing my own drivers while the Arduino platform offers a canned solution for just about everything I need.
Part of this porting activity requires that I benchmark the native calls as much as possible so I can squeeze every bit out of this processor. Much of what I'm looking for is "Low hanging fruit" that can be improved on.
The first issue I identified was the woefully slow implementation of "DigitalWrite", which I eventually found multiple references to throughout this forum. I may write a new abstraction for that, but I see very little need since it's very easy to perform bit wise operations on the PORT* registers.
The second low hanging fruit absolutely surprised me and I've found no reference to it here, so I thought I'd share.
In short, the function "void loop()" that our main code resides is REALLY SLOW.
Case 1 - Running code within the loop() function:
void loop()
{
PORTB ^= 0xFF;
}
Case 2 - Running code nested within a for ( ;; ) loop within the loop() function:
void loop()
{
for (;;) {
PORTB ^= 0xFF;
}
}
Case 1 can toggle the state of PORTB at 533kHz while Case 2 can toggle the state of PORTB at 1.6MHz. This is an impressive improvement.
Given that with everything else our code will be doing, as a ratio, this overhead may not amount to very much -- it does count for something and is very easy to work around at the expense of a for loop. Surprisingly, the compiled size of both cases was 4274 bytes. This tells me that the compiler's optimizer successfully optimized the code and there is no negative impact in terms of using more flash storage.
Attached are two screen shots from my scope. The first "loop" describes case 1 and "loop for" describes case 2.
For reference, this is running on an atmega32u4 at 16mhz.
Hope this helps someone!
Cheers!
- Jm