r/microcontrollers • u/fabytm • Sep 22 '20
C/C++ or Assembly for Embedded Systems? Which one leads to more optimized code?
https://www.youtube.com/watch?v=8LplMSFnBNY&list=PLeAb9_hv082weQ10WcvFfLBlNcCYXlQ4q&index=611
u/sillyvalleyserf Sep 23 '20
What are you optimizing for? Maximum functionality in minimum ROM/RAM? Maximum performance from a $2 MCU? Minimum time to market? Minimum development cost?
And what are you willing to trade off for the thing you're optimizing for?
Don't get me wrong, I'm not saying optimization is a waste of time. I love squeezing out cycles and bytes, and refactoring to get an order of magnitude improvement when I can. I'm literally an old school microprocessor assembly language coder. I once had the 8085 instruction set memorized in hex. I do mostly C++ for a living now.
My point is that there are good reasons to trade code size and performance for ease of development, and that sometimes the optimal choice for a particular situation is bloated code thrown together in a couple of weeks running on some cheap, stupid fast hardware (thanks to Moore's Law). Don't forget that modern hardware is orders of magnitude cheaper than a good developer's time.
And then in the rev 2 version... squeeze the heck out of that code, but do it smartly - know what your worst bottlenecks and biggest sources of bloat are, and attack them first.
2
u/tylerlarson Sep 23 '20
Any program you can write in C you can write in assembly, but not the other way around. So in theory you can write more efficient code in Assembly than C. But if your compiler is any good, you probably won't. It's way easier to master writing efficient code in C than in Assembly. Plus, microcontrollers often run exactly one instruction per cycle, regardless of which operation it is, so a lot of the optimization gains go out the window, and instead it becomes a matter of just not writing crappy code.
2
u/Triabolical_ Sep 23 '20
Generally speaking, an average developer will get better optimization with a good compiler than with assembly and will get there much faster.
For processors with weird architectures like the x86 the compiler walks all over the majority of developers in terms of perf.
1
3
u/fabytm Sep 22 '20
Hi everyone, In this episode of my educational series on Embedded Systems we are discussing the advantages and disadvantages of C/C++ and Assembly when writing code for Embedded Systems.
With Embedded Systems, it's always important to keep optimization in mind. Because of this, today we are taking a look at how choosing C/C++ or Assembly can impact how optimized your project will be.
If you're interested in this series, I’ve already explained GPIO, Interrupts, Timers, ADCs, UART, I2C, SPI, CAN Bus, Microcontroller Registers and Memory Addressing Modes in previous videos, here's the playlist: https://www.youtube.com/playlist?list=PLeAb9_hv082weQ10WcvFfLBlNcCYXlQ4q
I hope this series will help you out!