Electronic – Do global variables consume more power than local variables in embedded systems

cpower-consumptionprogramming

Today my colleague from work said that access to global variables on microcontrollers consumes more power than access to local variables, unfortunately she did not explain that. At the beginning, values of global varaibles are copied to RAM and then we operate on values from RAM, so how does it work that they consume more power? Are local variables stored in CPU registers, not in RAM ? We are programming in C language using GCC.

Best Answer

I suppose, that is what she had in mind. Variables stored in registers would need less power to access as there is no bus, address decoding and all that stuff you need for RAM access needed.

Global variables will most likely always be stored in RAM if you don't do some crazy stuff with your compiler (allocating a register for a variable).

But you can't be sure that local variables will not be stored in RAM. Your controller has only a very limited amount of registers available, some of them will be needed to perform other operations. If you need more local variables, you will end up on the RAM with them as well.

On calling a function, stuff gets pushed on the stack which is also RAM. Most of the code is stored in flash and reading from there consumes a lot more power than from RAM.

So if this was an argument to make you stop use global variables I'd say it's a rather weak one.

I actually found this (because of the hint of MSP430 in the comments):

ULP Advisor > Rule 7.1 Use local instead of global variables where possible

C compilers for micro-controllers in general and for MSP430 MCUs specifically allocate the variables declared in the global scope into the RAM location of the memory structure. On the other hand, local variables are first allocated into CPU registers (until the function runs out of the CPU registers for its local variables). Accesses to CPU registers are the most efficient and quickest, when compared to accesses to memory locations in RAM or even worse, in FLASH. Therefore, any global variables that are only accessed within one function can be safely relocated into the function local scope to optimize the memory access speed and power consumption.

So yes, she was probably thinking about this. But I wonder how much savings you can actually get.