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?
I'll assume you mean your application. In my experience, the major consumers of energy are, where #1 is most important:
- CPU usage
- 4G
- WiFi
- Bluetooth
- 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:
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.
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.
来源:https://stackoverflow.com/questions/28694878/battery-safe-coding