iKK
iKK

Reputation: 7012

CPU efficiency during animations

Using Swift5.2, iOS13.4,

I try to animate an analog clock with second-, minute- and hour hands.

The full example of the Clock can be found here: [Link](Here is the full example that I am using : Example Clock

Everything works - except that my iPhone heats up due to poor CPU efficiency in my angle calculations or angle-animation.

I've found that the below angle-animations are responsible for the iPhone warming up.

How can I improve my code so that it is more CPU efficient ?

Here is the angle calculation code:

public struct LocalTime {
    var hour: Double = 10.0
    var minute: Double = 10.0
    var second: Int = 25
}

let translateToRadian: CGFloat = CGFloat(Double.pi/180.0)

The following is calculated every 1 Second inside a Timer-tick:

secondHand.updateHandAngle(angle: CGFloat(localTime.second * 6) * translateToRadian, duration: 1.0, options: .curveLinear)
minuteHand.updateHandAngle(angle: CGFloat(localTime.minute * 6) * translateToRadian, duration: 0.5, options: .curveEaseInOut)
hourHand.updateHandAngle(angle: CGFloat(localTime.hour * 30) * translateToRadian, duration: 0.5, options: .curveEaseInOut)

Here is the updateAngle method:


func updateHandAngle(angle: CGFloat, duration: Double, options: UIView.AnimationOptions) {
    UIView.animate(withDuration: duration,
                          delay: 0.0,
                        options: options,
                     animations: { self.transform = CGAffineTransform(rotationAngle: angle) },
                     completion: { (finished: Bool) in return }
    )
}

Upvotes: 0

Views: 353

Answers (1)

gnasher729
gnasher729

Reputation: 52622

Assuming that "minute" and "hour" return an integer, it seems the minute hand only changes every minute, and the hour hand only every hour. So animate the hands to a new position only when it is needed, and one third of the CPU usage is gone.

Alternatively, if you moved the minutes hand every second by a little amount, any animation would be invisible. (Look at the minutes hand of a mechanical watch. It moves but you can't see it moving). So you wouldn't need animation at all, and think about how often you want to update the hour.

Upvotes: 1

Related Questions