Case Study in Optimization: Faster SPI on AVRs

Nerd Ralph
March 29, 2015

The Arduino Library provides functions like shiftOut() and digitalWrite().  These functions are simple and effective, but they are slow. Of course, they’re doing a lot more than just toggling bits. Faster isn’t always necessary and can sometimes lead to more difficult debugging.  And as Donald Knuth said,

…premature optimization is the root of all evil.

So what happens, when you do need to optimize? For example, if shiftOut() is too slow for your project, what do you do?  In Ralph’s post, Fastest AVR software SPI in the West, he breaks down different SPI code implementations into their assembly code.

To make the best optimization, you need to change compiler flags. So this is, in my opinion, an interesting case study in what kind of performance benefit you can get when you do some serious optimization.

Of course, you really shouldn’t, unless you need it…

Check out his post: Fastest AVR software SPI in the West

Knuth quote from his paper “StructuredProgrammingWithGoToStatements.”

Long comments, URLs, and code tend to get flagged for spam moderation. No need to resubmit.

ALL comments submitted with fake or throw-away services are deleted, regardless of content.

Don't be a dweeb.

Leave a comment

2 thoughts on “Case Study in Optimization: Faster SPI on AVRs

  1. I’ll see your Knuth quote, and raise you with an Einstein quote: “Unthinking respect for authority is the greatest enemy of truth.”
    The big caveat in Knuth’s quote is how you define “premature”. I focus on making lean/efficient code, and try to avoid optimizations that increase code size and complexity. Less code is easier to maintain and understand.

  2. Changing the compiler flags may help in this case. But you can simply inline this assembler thing and make a nice template out of it. Then you can use this with any Arduino pin, very simple, from the ide, without any modification.