8

I am looking at implementing a non-trivial finite state machine (specified as a UML hierarchical statechart) on a 32-bit MCU with gcc.

Are there any rules of thumb what works better and what works less well? My gut says that a switch-based (or even computed goto) implementation should be slightly more performant while a function-pointer based transition table is generally reputed to be more maintainable.

Also: has anybody evaluated Boost MSM for embedded applications? I know that Boost MSM is generally lauded as being very efficient, but for embedded applications efficiency might be measured differently than in the world of PC programming.

Does anybody know what the compiled state machine engine of MSM looks like? More like a switch jumptable or more like a function pointer transition table? Does it use dynamic memory allocation or can it used statically?

ARF
  • 5,169
  • 9
  • 42
  • 69
  • I would stay away from the Boost MSM (and C++ templates in general) as they blow up the code size really fast. – jms Mar 05 '16 at 23:56
  • There are some other [gotchas](http://electronics.stackexchange.com/questions/3027/is-c-suitable-for-embedded-systems) in C++ to be aware of... – Matt Young Mar 06 '16 at 02:26
  • @jms That's like saying that a woodcutter should stay away from sharp tools and use a hammer instead because with sharp tools he might cut himself. Templates are a sharp tool, which - when used in the right way - can increase the speed and reduce the size of you code, especially for small micro-controllers. When used in the wrong way - well, *any* tool can be used in the wrong way! – Wouter van Ooijen Mar 06 '16 at 08:08

2 Answers2

8

I'd be surprised if there's a big difference on a 32-bit MCU. Avoiding conditional branches could save you a few cycles, but are you really going to succeed or fail based on a few cycles? The number of wait states on your RAM and ROM are probably at least as important. So is the CPU instruction set.

Premature optimization is the root of all evil. Start with what's easier to implement and maintain, and only optimize where necessary based on profiling.

Adam Haun
  • 21,331
  • 4
  • 50
  • 91
  • I would expect that the influence on performance of a state machine framework (whether DIY or from some libary) - as opposeds to the actions - is very small. So as Adam says: code for readability first. An second. And third. (A at the 10th position: profile. Local optimization is way below that.) – Wouter van Ooijen Mar 06 '16 at 08:13
3

For one UML implementation on embedded take a look at QP framework -> http://www.state-machine.com . Both C and C++ variants are available. The accompanying GUI (QM) even allows to code using UML notation. The framework is small enough to run on Arduino; 32-bitters are easy.

Oleg Mazurov
  • 3,231
  • 1
  • 14
  • 17