Workflow for solving power issues:

Use Xcode Energy Gauge first to figure out which area consumes power (network and Motion, positioning…). Use Time Profiler to locate and resolve problems (Instruments template) and get good feedback from users.

Three principles:
  • Do it never/ Do it less. Do less, good)

For example: network request, compress data first

  • Do it at a better time

Network requests, using caching mechanisms, setting content validation (whether the required data has been updated), or the expiration time of the cache

  • Do it efficiently

Merge network requests. Requesting a large amount of data at one time saves power compared to requesting a small amount of data multiple times

(Analogy with CPU, too many threads are bad. Open the thread, there will be consumption.


It’s very simple. Put your phone on your desk, launch your app in Xcode, and do nothing. If the power consumption is high, it’s not appropriate

WWDC Energy Debug Gauge in the Xcode Debug bar is recommended.

(Tuning performance, all with the real machine. Older machines work better)

Energy Debug Gauge Visually and intuitively

It can be seen that the current power consumption of mobile phones is low, high and high. The three stages of Apple, a little bit less detailed. (Utilization, Current Impact, upper left)

The Average energy consumption of APP is clear at a glance (Average on the upper right).

At any given moment, what is being consumed. CPU, network, file I/O, location, which is consumed. (Energy Impact in the middle)


Such as:

Analyze the CPU usage of the time profile, (can know the code execution, according to the function call consumption. Identify the powerful ones and eliminate the unnecessary ones.

Analyze the network profile of network activities and the location profile of positioning activities


This article sample code: solve two problems, to CoreMotion update Settings filter, eliminate frequent log uploads

Power consumption is high here. It’s stable

It’s mainly the CPU and network requests that consume power.


Using Instruments’ Time Profiler analysis,

You can first enlarge the time line above, and then select a time range for further analysis in the Call tree.

Time Profiler options are broken down by thread by default, plus a hidden system call function.

(The system executes the function, can refer to, exactly what happened. The system can’t be changed. Can change their own source code)

In the table of the call tree, expand by weight, and the ones to kill are the heavy ones that take time.

Next, expand the main thread. Hold down the Option key and click on the triangle to the left of the main thread to expand a lot.

Thunk for… thunk for… CMDeviceMotion? .

Call a time consuming method, CatPhotoTableViewCell. PanImage, pictured above, in 454 milliseconds, accounting for 419 milliseconds.

Click on the details to see the code.

In the viewDidLoad method of CatFeedViewController, there is a tilt setting

motionManager.startDeviceMotionUpdates(to: .main, withHandler:{ deviceMotion, error in
            guard let deviceMotion = deviceMotion else { return }
            let xRotationRate = CGFloat(deviceMotion.rotationRate.x)
            let yRotationRate = CGFloat(deviceMotion.rotationRate.y)
            letZRotationRate = CGFloat (deviceMotion. RotationRate. Z) / / > y z, this movement is stuck up / / > x + y z, this action is inclined to become warped upif abs(yRotationRate) > (abs(xRotationRate) + abs(zRotationRate)) {
                for cell in self.tableView.visibleCells as! [CatPhotoTableViewCell] {
                    cell.panImage(with: yRotationRate)
                }
              }
  })
Copy the code

Now the code display bar (the original Call Tree table) has a small Xcode icon in the upper right corner. Click to return to Xcode debug code.

Keep calling cell.panimage (with: yRotationRate) without moving your phone.

Set the cell. PanImage call to exceed the minimum cell amplitude. It’s small. It doesn’t work. Add a property to record lastY Settings to filter out small jitter on the phone.

Private var lastY = 0.0 override funcviewDidLoad() {
        super.viewDidLoad()
        ......
        motionManager.startDeviceMotionUpdates(to: .main, withHandler:{ deviceMotion, error in
            guard let deviceMotion = deviceMotion else { return} / / add the two lines of guard abs (self. LastY - deviceMotion. RotationRate. Y) > 0.1else { return }
            self.lastY = deviceMotion.rotationRate.y

            let xRotationRate = CGFloat(deviceMotion.rotationRate.x)
            let yRotationRate = CGFloat(deviceMotion.rotationRate.y)
            let zRotationRate = CGFloat(deviceMotion.rotationRate.z)
              if abs(yRotationRate) > (abs(xRotationRate) + abs(zRotationRate)) {
                for cell in self.tableView.visibleCells as! [CatPhotoTableViewCell] {
                    cell.panImage(with: yRotationRate)
                }
              }
        })
    }
Copy the code

There is also the problem of using Timer to send logs. The CPU has no idle time, which is very expensive.

See the Demo Code at the end of this article for details.

The last such

It will go down slowly, as for low battery consumption. It takes about two minutes. It won’t fit on one screen.


There is a problem with the Energy Log of Instruments, which is connected to the Xcode real-time debugging section

Instruments’ Energy Log template is not very useful

Because mobile phone online debugging is not possible. Energy is empty, or No Data,

This is a long-standing Apple bug (see Apple Forum).

The Energy Log template has a variety of modules, including screen brightness, positioning, Bluetooth, GPU, and network power consumption, including WiFi and cellular networks.


Trying to charge your phone while debugging for battery loss is not a good idea.

Try using the Energy Log template for wireless Instruments, and the result is the same.

Wireless Xcode debugging consumes power and no data.


For wireless Instruments debugging, first set Xcode wireless Debug.

Wireless debug is hidden in Windows > Devices and Simulators in Xcode.

In effect, instead of a cable connection, you connect to Xcode using a shared wireless network.

There will be a network Icon. There will be a connected message.

The diagram below:

See the blog How to Use Wireless Debugging on Xcode 9 for more information

And then you can set up your Instruments wireless device debugging,

See apple’s Energy Efficiency Guide for iOS Apps for more information


WWDC says to see, import the offline log. (Until a few months ago, it worked.)

In the phone’s Settings, select “Logging” in the developer option, and click “Energy” to start recording:

After using your app for a while, click Logging in the Developer option and import the power consumption log data to the Energy Log template of Instruments.

Not for the old version (11.4), no data available. When operating, the mobile phone setting APP, but also always flash back.

I upgraded my phone to the latest version (12.1, 20181127). I tried many times, but it didn’t work. I guess it is completely dead now

(In this article, you’ve rebooted your phone and upgraded it. Have not tried to restart the computer)


A little wet, easy digestion

It’s not good to consume electricity.

Hard disk writing and network requests are both high-power operations.

Network requests are particularly power-hungry, and for every network request, a mobile device needs to use its cellular network antenna to send radio waves.

The quality and type of network also have a big impact on power consumption. Using Wi-Fi is much cheaper than using 3G or 4G. It is cheaper to use 4G than 3G because the signal is stronger.

A timer. Use it if you can. (NSTimer)

In general, apps do a lot of useless work with timers.

For example, if you have a list screen with a banner timer at the top, you can pause the timer by sliding down to the point where the banner is no longer visible. Slide up, see banner, can resume.

Similarly, enter the sub-interface, you can choose to pause Timer, or release,…

Example: it is not good to do a lot of repetitive work on a regular basis. It is possible that every time the system goes to sleep (the system is about to lower its energy level), the system wakes up again and starts to consume power.

positioning

Similar to Internet requests, mobile device positioning sends signals through A GPS antenna, which also consumes power.

If the APP often obtains the precise positioning of the mobile device, the higher the positioning accuracy, the more serious the energy consumption. Suggest using strategy, mobile phone burden will be much less.

(🌰, Deferred location updates, location updates delayed until x meters or more than xx seconds have been moved),

Significant location change, wake up,

Region monitoring, which monitors users entering or leaving a specific geographical area)

Motion physics engine, dynamic effects update status, pretty power hungry.

Using compasses, gyroscopes and accelerometers is expensive.


Related codes:Github.com/BoxDengJZ/I…

More information:

WWDC 2015 Debugging Energy Issues

Video tutorial, Practical – Instruments


This Demo uses a 500 px API.


It turned out that someone had written about it,

So awkward

On second thought, I can write what he didn’t say. Apple updates too fast, people change things