Battery-safe coding

I was wondering if there are some rules or hints how to prevent battery drain directly while coding. I know that there may be some ways to code to minimize workload on the processor or prevent leaks. However, does anybody have something like a guide or a something like a "checklist" besides the usual suspects like location service and internet connection?


Solution 1:

I'll assume you mean your application. In my experience, the major consumers of energy are, where #1 is most important:

  1. CPU usage
  2. 4G
  3. WiFi
  4. Bluetooth
  5. Memory

Whether 4G or WiFi is worse depends upon your usage, e.g. whether you are talking with a poor signal over your cellular network or are streaming video over your WiFi. GPS depends upon if you are using it. If you are getting turn by turn directions, it'll turn your phone into a little heater and drain your battery very quickly.

Minimizing 4G, WiFi, and Bluetooth usage is pretty straight forward. I not sure it's possible to reduce the energy used by memory in any practical way.

CPU usage is the greatest potential energy hog because it can continuously suck down electrons all of the time. Thankfully, modern processors shut down when doing nothing, i.e. idling. This is called dropping into an idle / C-state. As you can guess, a cell phone is doing nothing pretty much most of the time.

There are ways you can write your program to minimize CPU energy usage. Actually, a better way of saying this is that there are ways you can defeat these energy saving features by writing your program wrong. If the CPU goes to sleep to minimize power then waking it up increases energy usage. Another factor to consider is how long the CPU is asleep. The longer you can leave the processor idle, the deeper a sleep state it can enter, and deeper sleep states use less power.

So what do you need to do to minimize your CPU usage? You want to use the CPU less, or to say it another way, have your program get done whatever it’s doing faster. Also, increase the length of time that your program is idle.

Now let's take a look at some concrete things you can do:

  1. Have your program do whatever it's doing as fast as possible. Do this by finding the fastest algorithm and implementing it in the most efficient way possible. To say it another way, optimize.

  2. Minimize checking on events. The more you check on whether an event occurred, the more you wake up the processor, the less likely it can drop into a really deep sleep state. Do this by figuring out the maximum interval that you have to check for some event while still maintaining performance.