axiom-energy by charleswiltgen/axiom
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-energy能源问题表现为电池耗电快、设备发热以及应用商店差评。核心原则:先测量后优化。使用 Power Profiler 识别主导子系统(CPU/GPU/网络/定位/显示),然后应用针对性修复。
关键洞察:开发者通常不知道从何处开始审计。本技能提供系统化诊断,而非猜测。
要求:iOS 26+、Xcode 26+、Instruments 中的 Power Profiler
开发者提出的实际问题,本技能可解答:
→ 本技能涵盖使用 Power Profiler 工作流来识别主导子系统并进行针对性修复
→ 本技能提供决策树:CPU 与 GPU 与网络诊断,包含特定模式
→ 本技能涵盖定时器容差、定位精度权衡以及审计清单
→ 本技能涵盖后台执行模式、BGTasks 和 EMRCA 原则
→ 本技能演示优化前后的 Power Profiler 对比工作流
如果出现以下任何情况,请怀疑存在能源效率问题:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
在优化代码之前,务必先运行 Power Profiler:
1. 通过无线方式将 iPhone 连接到 Xcode(无线调试)
2. Xcode → Product → Profile (Cmd+I)
3. 选择 Blank 模板
4. 点击 "+" → 添加 "Power Profiler" 工具
5. 可选:添加 "CPU Profiler" 以进行关联分析
6. 点击 Record
7. 正常使用您的应用 2-3 分钟
8. 点击 Stop
为何使用无线连接:当设备通过线缆充电时,电源指标显示为 0。使用无线调试以获得准确读数。
展开 Power Profiler 轨道并检查每个应用的指标:
| 轨道 | 含义 | 高值表示 |
|---|---|---|
| CPU Power Impact | 处理器活动 | 计算、定时器、解析 |
| GPU Power Impact | 图形渲染 | 动画、模糊效果、Metal |
| Display Power Impact | 屏幕使用 | 亮度、常亮内容 |
| Network Power Impact | 无线电活动 | 请求、下载、轮询 |
寻找:在您的应用使用期间,哪个子系统显示出最高的持续值。
一旦识别出主导子系统,请使用下面的决策树。
User reports energy issue?
│
├─ CPU Power Impact dominant?
│ ├─ Continuous high impact?
│ │ ├─ Timers running? → Pattern 1: Timer Efficiency
│ │ ├─ Polling data? → Pattern 2: Push vs Poll
│ │ └─ Processing in loop? → Pattern 3: Lazy Loading
│ ├─ Spikes during specific actions?
│ │ ├─ JSON parsing? → Cache parsed results
│ │ ├─ Image processing? → Move to background, cache
│ │ └─ Database queries? → Index, batch, prefetch
│ └─ High background CPU?
│ ├─ Location updates? → Pattern 4: Location Efficiency
│ ├─ BGTasks running too long? → Pattern 5: Background Execution
│ └─ Audio session active? → Stop when not playing
│
├─ Network Power Impact dominant?
│ ├─ Many small requests?
│ │ └─ Batch into fewer large requests
│ ├─ Polling pattern detected?
│ │ └─ Convert to push notifications → Pattern 2
│ ├─ Downloads in foreground?
│ │ └─ Use discretionary background URLSession
│ └─ High cellular usage?
│ └─ Defer to WiFi when possible
│
├─ GPU Power Impact dominant?
│ ├─ Continuous animations?
│ │ └─ Stop when view not visible
│ ├─ Blur effects (UIVisualEffectView)?
│ │ └─ Reduce or remove, use solid colors
│ ├─ High frame rate animations?
│ │ └─ Audit secondary frame rates → Pattern 6
│ └─ Metal rendering?
│ └─ Implement frame limiting
│
├─ Display Power Impact dominant?
│ ├─ Light backgrounds on OLED?
│ │ └─ Implement Dark Mode (up to 70% savings)
│ ├─ High brightness content?
│ │ └─ Use darker UI elements
│ └─ Screen always on?
│ └─ Allow screen to sleep when appropriate
│
└─ Location causing drain? (check CPU lane + location icon)
├─ Continuous updates?
│ └─ Switch to significant-change monitoring
├─ High accuracy (kCLLocationAccuracyBest)?
│ └─ Reduce to kCLLocationAccuracyHundredMeters
└─ Background location?
└─ Evaluate if truly needed → Pattern 4
问题:定时器将 CPU 从空闲状态唤醒,消耗大量能源。
// BAD: Timer fires exactly every 1.0 seconds
// Prevents system from batching with other timers
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
self.updateUI()
}
// GOOD: 10% tolerance allows system to batch timers
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
self.updateUI()
}
timer.tolerance = 0.1 // 10% tolerance minimum
// BETTER: Use Combine Timer with tolerance
Timer.publish(every: 1.0, tolerance: 0.1, on: .main, in: .default)
.autoconnect()
.sink { [weak self] _ in
self?.updateUI()
}
.store(in: &cancellables)
// BEST: Don't use timer at all — react to events
NotificationCenter.default.publisher(for: .dataDidUpdate)
.sink { [weak self] _ in
self?.updateUI()
}
.store(in: &cancellables)
关键点:
问题:轮询(每 N 秒检查一次服务器)使无线电保持活动状态并消耗电池。
// BAD: Polls server every 5 seconds
// Radio stays active, massive battery drain
Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
self?.fetchLatestData() // Network request every 5 seconds
}
// GOOD: Server pushes when data changes
// Radio only active when there's actual new data
// 1. Register for remote notifications
UIApplication.shared.registerForRemoteNotifications()
// 2. Handle background notification
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
guard let _ = userInfo["content-available"] else {
completionHandler(.noData)
return
}
Task {
do {
let hasNewData = try await fetchLatestData()
completionHandler(hasNewData ? .newData : .noData)
} catch {
completionHandler(.failed)
}
}
}
后台推送的服务器负载:
{
"aps": {
"content-available": 1
},
"custom-data": "your-payload"
}
关键点:
apns-priority: 5(节能)apns-priority: 10问题:预先加载所有数据会导致 CPU 峰值和内存压力。
// BAD: Creates and renders ALL views upfront
// From WWDC25-226: This caused CPU spike and hang
VStack {
ForEach(videos) { video in
VideoCardView(video: video) // Creates ALL thumbnails immediately
}
}
// GOOD: Only creates visible views
// From WWDC25-226: Reduced CPU power impact from 21 to 4.3
LazyVStack {
ForEach(videos) { video in
VideoCardView(video: video) // Creates on-demand
}
}
// BAD: Parses JSON file on every location update
// From WWDC25-226: Caused continuous CPU drain during commute
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
// Called every location change!
let data = try? Data(contentsOf: rulesFileURL)
let rules = try? JSONDecoder().decode([RecommendationRule].self, from: data)
return filteredVideos(using: rules)
}
// GOOD: Parse once, reuse cached result
// From WWDC25-226: Eliminated CPU drain
private lazy var cachedRules: [RecommendationRule] = {
let data = try? Data(contentsOf: rulesFileURL)
return (try? JSONDecoder().decode([RecommendationRule].self, from: data)) ?? []
}()
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
return filteredVideos(using: cachedRules) // No parsing!
}
关键点:
LazyVStack、LazyHStack、LazyVGrid问题:连续的位置更新使 GPS 保持活动状态,迅速消耗电池。
// BAD: Continuous updates with best accuracy
// GPS stays active constantly, massive battery drain
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation() // Never stops!
// GOOD: Reduced accuracy, significant-change monitoring
let locationManager = CLLocationManager()
// Use appropriate accuracy (100m is fine for most apps)
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// Use distance filter to reduce updates
locationManager.distanceFilter = 100 // Only update every 100 meters
// For background: Use significant-change monitoring
locationManager.startMonitoringSignificantLocationChanges()
// Stop when done
func stopTracking() {
locationManager.stopUpdatingLocation()
locationManager.stopMonitoringSignificantLocationChanges()
}
// BEST: Modern async API with automatic stationary detection
for try await update in CLLocationUpdate.liveUpdates() {
if update.stationary {
// Device stopped moving — system pauses updates automatically
// Switch to CLMonitor for region monitoring
break
}
handleLocation(update.location)
}
精度对比(电池影响):
| 精度 | 电池影响 | 使用场景 |
|---|---|---|
kCLLocationAccuracyBest | 非常高 | 仅限导航应用 |
kCLLocationAccuracyNearestTenMeters | 高 | 健身追踪 |
kCLLocationAccuracyHundredMeters | 中等 | 商店定位器 |
kCLLocationAccuracyKilometer | 低 | 天气应用 |
| 显著位置变化 | 非常低 | 后台更新 |
问题:运行时间过长或过于频繁的后台任务会消耗电池。
您的后台工作必须:
// BAD: Requests unlimited background time
// System will terminate after ~30 seconds anyway
var backgroundTask: UIBackgroundTaskIdentifier = .invalid
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTask = application.beginBackgroundTask {
// Expiration handler — but task runs too long
}
// Long operation that may not complete
performLongOperation()
}
// GOOD: Finish quickly, save progress, notify system
var backgroundTask: UIBackgroundTaskIdentifier = .invalid
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTask = application.beginBackgroundTask(withName: "Save State") { [weak self] in
// Expiration handler — clean up immediately
self?.saveProgress()
if let task = self?.backgroundTask {
application.endBackgroundTask(task)
}
self?.backgroundTask = .invalid
}
// Quick operation
saveEssentialState()
// End task as soon as done — don't wait for expiration
application.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
// BEST: Let system schedule at optimal time (charging, WiFi)
func scheduleBackgroundProcessing() {
let request = BGProcessingTaskRequest(identifier: "com.app.maintenance")
request.requiresNetworkConnectivity = true
request.requiresExternalPower = true // Only when charging
try? BGTaskScheduler.shared.submit(request)
}
// Register handler at app launch
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.app.maintenance",
using: nil
) { task in
self.handleMaintenance(task: task as! BGProcessingTask)
}
// NEW iOS 26: Continue user-initiated tasks with progress UI
let request = BGContinuedProcessingTaskRequest(
identifier: "com.app.export",
title: "Exporting Photos",
subtitle: "23 of 100 photos"
)
try? BGTaskScheduler.shared.submit(request)
问题:次要动画以高于所需帧率运行会增加 GPU 功耗。
// BAD: Secondary animation runs at 60fps
// When primary content only needs 30fps, this wastes power
UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat]) {
self.subtitleLabel.alpha = 0.5
} completion: { _ in
self.subtitleLabel.alpha = 1.0
}
// GOOD: Explicitly set preferred frame rate
let displayLink = CADisplayLink(target: self, selector: #selector(updateAnimation))
displayLink.preferredFrameRateRange = CAFrameRateRange(
minimum: 10,
maximum: 30, // Match primary content
preferred: 30
)
displayLink.add(to: .current, forMode: .default)
来自 WWDC22-10083:通过将次要动画帧率与主要内容对齐,可节省高达 20% 的电池电量。
waitsForConnectivity 以避免失败的连接尝试?allowsExpensiveNetworkAccess 设置为 false?kCLLocationAccuracyBest)?distanceFilter 以减少更新频率?endBackgroundTask?requiresExternalPower 的 BGProcessingTask?诱惑:"推送通知很复杂。轮询更简单。"
现实:
时间成本对比:
反驳模板:"推送通知设置需要几个小时,但轮询将确保我们在电池设置中排在最前面。用户会主动卸载耗电的应用。2 小时的投资可以防止持续的声誉损害。"
诱惑:"用户期望精确定位。让我们使用 kCLLocationAccuracyBest。"
现实:
kCLLocationAccuracyBest:GPS + WiFi + 蜂窝三角定位 = 巨大的消耗kCLLocationAccuracyHundredMeters:对于 95% 的使用场景足够好时间成本对比:
反驳模板:"对于[使用场景],100 米精度已经足够。像 Google Maps 这样的导航应用需要最佳精度,但我们显示的是[商店位置 / 天气 / 大致区域]。精度的差异对用户来说难以察觉,但电池差异是巨大的。"
诱惑:"动画让应用感觉生动和精致。"
现实:
时间成本对比:
反驳模板:"我们可以保留动画,但应该在视图不可见时暂停它。这是一个 5 分钟的更改,可以防止用户不看屏幕时的 GPU 消耗。"
诱惑:"能源优化是锦上添花。我们可以在 v1.1 中做。"
现实:
时间成本对比:
反驳模板:"发布前进行 15 分钟的 Power Profiler 会话可以捕捉到主要的能源问题。如果我们带着电池问题发布,用户会在第一天就看到我们在电池设置中排在最前面,并留下 1 星评价。让我快速检查一下 — 这比损害控制要快。"
症状:打开 Library 面板时,CPU 功耗影响从 1 跃升至 21。UI 卡住。
使用 Power Profiler 诊断:
VideoCardView 的 body 被调用了数百次VStack 预先创建了所有视频缩略图修复:
// Before: VStack (eager)
VStack {
ForEach(videos) { video in
VideoCardView(video: video)
}
}
// After: LazyVStack (on-demand)
LazyVStack {
ForEach(videos) { video in
VideoCardView(video: video)
}
}
结果:CPU 功耗影响从 21 降至 4.3。UI 不再卡住。
症状:用户通勤时报告电池耗电严重。开发者在办公桌前无法复现。
使用设备上的 Power Profiler 诊断:
videoSuggestionsForLocation 消耗 CPU修复:
// Before: Parse on every call
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
let data = try? Data(contentsOf: rulesFileURL)
let rules = try? JSONDecoder().decode([RecommendationRule].self, from: data)
return filteredVideos(using: rules)
}
// After: Parse once, cache
private lazy var cachedRules: [RecommendationRule] = {
let data = try? Data(contentsOf: rulesFileURL)
return (try? JSONDecoder().decode([RecommendationRule].self, from: data)) ?? []
}()
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
return filteredVideos(using: cachedRules)
}
结果:消除了移动期间的 CPU 峰值。电池耗电问题得到解决。
症状:即使不播放音乐,应用也会耗电。
诊断:
修复:
// Before: Never deactivate
func playTrack(_ track: Track) {
try? AVAudioSession.sharedInstance().setActive(true)
player.play()
}
func stopPlayback() {
player.stop()
// Audio session still active!
}
// After: Deactivate when done
func stopPlayback() {
player.stop()
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
}
// Even better: Use AVAudioEngine auto-shutdown
let engine = AVAudioEngine()
engine.isAutoShutdownEnabled = true // Automatically powers down when idle
结果:后台音频硬件断电。电池耗电问题消除。
检测并适应用户启用低电量模式:
// Check current state
if ProcessInfo.processInfo.isLowPowerModeEnabled {
reduceEnergyUsage()
}
// React to changes
NotificationCenter.default.publisher(for: .NSProcessInfoPowerStateDidChange)
.sink { [weak self] _ in
if ProcessInfo.processInfo.isLowPowerModeEnabled {
self?.reduceEnergyUsage()
} else {
self?.restoreNormalOperation()
}
}
.store(in: &cancellables)
func reduceEnergyUsage() {
// Pause optional activities
// Reduce animation frame rates
// Increase timer intervals
// Defer network requests
// Stop location updates if not critical
}
import MetricKit
class EnergyMetricsManager: NSObject, MXMetricManagerSubscriber {
static let shared = EnergyMetricsManager()
func startMonitoring() {
MXMetricManager.shared.add(self)
}
func didReceive(_ payloads: [MXMetricPayload]) {
for payload in payloads {
if let cpuMetrics = payload.cpuMetrics {
// Monitor CPU time
let foregroundCPU = cpuMetrics.cumulativeCPUTime
logMetric("foreground_cpu", value: foregroundCPU)
}
if let locationMetrics = payload.locationActivityMetrics {
// Monitor location usage
let backgroundLocation = locationMetrics.cumulativeBackgroundLocationTime
logMetric("background_location", value: backgroundLocation)
}
}
}
}
在 Xcode Organizer 中检查 Battery Usage 面板以获取现场数据:
1. Connect device wirelessly
2. Product → Profile → Blank → Add Power Profiler
3. Record 2-3 minutes of usage
4. Identify dominant subsystem (CPU/GPU/Network/Display)
5. Apply targeted fix from patterns above
6. Record again to verify improvement
| 优化 | 潜在节省 |
|---|---|
| OLED 上的深色模式 | 显示功耗节省高达 70% |
| 帧率对齐 | GPU 功耗节省高达 20% |
| 推送与轮询 | 网络效率提高 100 倍 |
| 降低定位精度 | GPS 功耗节省 50-90% |
| 定时器容差 | 显著节省 CPU 功耗 |
| 惰性加载 | 消除启动时的 CPU 峰值 |
axiom-energy-ref — 包含所有代码示例的完整 API 参考axiom-energy-diag — 基于症状的故障排除决策树axiom-background-processing — 后台任务机制(为什么任务不运行)axiom-performance-profiling — 通用 Instruments 工作流axiom-memory-debugging — 内存泄漏诊断(通常与能源相关)axiom-networking — 网络优化模式axiom-timer-patterns — 定时器崩溃预防和生命周期安全最后更新:2025-12-26 平台:iOS 26+、iPadOS 26+ 状态:生产就绪的能源优化模式
每周安装量
96
代码仓库
GitHub Stars
601
首次出现
Jan 21, 2026
安全审计
安装于
opencode80
codex76
claude-code75
gemini-cli73
cursor73
github-copilot70
Energy issues manifest as battery drain, hot devices, and poor App Store reviews. Core principle : Measure before optimizing. Use Power Profiler to identify the dominant subsystem (CPU/GPU/Network/Location/Display), then apply targeted fixes.
Key insight : Developers often don't know where to START auditing. This skill provides systematic diagnosis, not guesswork.
Requirements : iOS 26+, Xcode 26+, Power Profiler in Instruments
Real questions developers ask that this skill answers:
→ The skill covers Power Profiler workflow to identify dominant subsystem and targeted fixes
→ The skill provides decision tree: CPU vs GPU vs Network diagnosis with specific patterns
→ The skill covers timer tolerance, location accuracy trade-offs, and audit checklists
→ The skill covers background execution patterns, BGTasks, and EMRCA principles
→ The skill demonstrates before/after Power Profiler comparison workflow
If you see ANY of these, suspect energy inefficiency:
ALWAYS run Power Profiler FIRST before optimizing code:
1. Connect iPhone wirelessly to Xcode (wireless debugging)
2. Xcode → Product → Profile (Cmd+I)
3. Select Blank template
4. Click "+" → Add "Power Profiler" instrument
5. Optional: Add "CPU Profiler" for correlation
6. Click Record
7. Use your app normally for 2-3 minutes
8. Click Stop
Why wireless : When device is charging via cable, power metrics show 0. Use wireless debugging for accurate readings.
Expand the Power Profiler track and examine per-app metrics:
| Lane | Meaning | High Value Indicates |
|---|---|---|
| CPU Power Impact | Processor activity | Computation, timers, parsing |
| GPU Power Impact | Graphics rendering | Animations, blur, Metal |
| Display Power Impact | Screen usage | Brightness, always-on content |
| Network Power Impact | Radio activity | Requests, downloads, polling |
Look for : Which subsystem shows highest sustained values during your app's usage.
Once you identify the dominant subsystem, use the decision trees below.
User reports energy issue?
│
├─ CPU Power Impact dominant?
│ ├─ Continuous high impact?
│ │ ├─ Timers running? → Pattern 1: Timer Efficiency
│ │ ├─ Polling data? → Pattern 2: Push vs Poll
│ │ └─ Processing in loop? → Pattern 3: Lazy Loading
│ ├─ Spikes during specific actions?
│ │ ├─ JSON parsing? → Cache parsed results
│ │ ├─ Image processing? → Move to background, cache
│ │ └─ Database queries? → Index, batch, prefetch
│ └─ High background CPU?
│ ├─ Location updates? → Pattern 4: Location Efficiency
│ ├─ BGTasks running too long? → Pattern 5: Background Execution
│ └─ Audio session active? → Stop when not playing
│
├─ Network Power Impact dominant?
│ ├─ Many small requests?
│ │ └─ Batch into fewer large requests
│ ├─ Polling pattern detected?
│ │ └─ Convert to push notifications → Pattern 2
│ ├─ Downloads in foreground?
│ │ └─ Use discretionary background URLSession
│ └─ High cellular usage?
│ └─ Defer to WiFi when possible
│
├─ GPU Power Impact dominant?
│ ├─ Continuous animations?
│ │ └─ Stop when view not visible
│ ├─ Blur effects (UIVisualEffectView)?
│ │ └─ Reduce or remove, use solid colors
│ ├─ High frame rate animations?
│ │ └─ Audit secondary frame rates → Pattern 6
│ └─ Metal rendering?
│ └─ Implement frame limiting
│
├─ Display Power Impact dominant?
│ ├─ Light backgrounds on OLED?
│ │ └─ Implement Dark Mode (up to 70% savings)
│ ├─ High brightness content?
│ │ └─ Use darker UI elements
│ └─ Screen always on?
│ └─ Allow screen to sleep when appropriate
│
└─ Location causing drain? (check CPU lane + location icon)
├─ Continuous updates?
│ └─ Switch to significant-change monitoring
├─ High accuracy (kCLLocationAccuracyBest)?
│ └─ Reduce to kCLLocationAccuracyHundredMeters
└─ Background location?
└─ Evaluate if truly needed → Pattern 4
Problem : Timers wake the CPU from idle states, consuming significant energy.
// BAD: Timer fires exactly every 1.0 seconds
// Prevents system from batching with other timers
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
self.updateUI()
}
// GOOD: 10% tolerance allows system to batch timers
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
self.updateUI()
}
timer.tolerance = 0.1 // 10% tolerance minimum
// BETTER: Use Combine Timer with tolerance
Timer.publish(every: 1.0, tolerance: 0.1, on: .main, in: .default)
.autoconnect()
.sink { [weak self] _ in
self?.updateUI()
}
.store(in: &cancellables)
// BEST: Don't use timer at all — react to events
NotificationCenter.default.publisher(for: .dataDidUpdate)
.sink { [weak self] _ in
self?.updateUI()
}
.store(in: &cancellables)
Key points :
Problem : Polling (checking server every N seconds) keeps radios active and drains battery.
// BAD: Polls server every 5 seconds
// Radio stays active, massive battery drain
Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
self?.fetchLatestData() // Network request every 5 seconds
}
// GOOD: Server pushes when data changes
// Radio only active when there's actual new data
// 1. Register for remote notifications
UIApplication.shared.registerForRemoteNotifications()
// 2. Handle background notification
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
guard let _ = userInfo["content-available"] else {
completionHandler(.noData)
return
}
Task {
do {
let hasNewData = try await fetchLatestData()
completionHandler(hasNewData ? .newData : .noData)
} catch {
completionHandler(.failed)
}
}
}
Server payload for background push :
{
"aps": {
"content-available": 1
},
"custom-data": "your-payload"
}
Key points :
apns-priority: 5 for non-urgent updates (energy efficient)apns-priority: 10 only for time-sensitive alertsProblem : Loading all data upfront causes CPU spikes and memory pressure.
// BAD: Creates and renders ALL views upfront
// From WWDC25-226: This caused CPU spike and hang
VStack {
ForEach(videos) { video in
VideoCardView(video: video) // Creates ALL thumbnails immediately
}
}
// GOOD: Only creates visible views
// From WWDC25-226: Reduced CPU power impact from 21 to 4.3
LazyVStack {
ForEach(videos) { video in
VideoCardView(video: video) // Creates on-demand
}
}
// BAD: Parses JSON file on every location update
// From WWDC25-226: Caused continuous CPU drain during commute
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
// Called every location change!
let data = try? Data(contentsOf: rulesFileURL)
let rules = try? JSONDecoder().decode([RecommendationRule].self, from: data)
return filteredVideos(using: rules)
}
// GOOD: Parse once, reuse cached result
// From WWDC25-226: Eliminated CPU drain
private lazy var cachedRules: [RecommendationRule] = {
let data = try? Data(contentsOf: rulesFileURL)
return (try? JSONDecoder().decode([RecommendationRule].self, from: data)) ?? []
}()
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
return filteredVideos(using: cachedRules) // No parsing!
}
Key points :
LazyVStack, LazyHStack, LazyVGrid for large collectionsProblem : Continuous location updates keep GPS active, draining battery rapidly.
// BAD: Continuous updates with best accuracy
// GPS stays active constantly, massive battery drain
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation() // Never stops!
// GOOD: Reduced accuracy, significant-change monitoring
let locationManager = CLLocationManager()
// Use appropriate accuracy (100m is fine for most apps)
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// Use distance filter to reduce updates
locationManager.distanceFilter = 100 // Only update every 100 meters
// For background: Use significant-change monitoring
locationManager.startMonitoringSignificantLocationChanges()
// Stop when done
func stopTracking() {
locationManager.stopUpdatingLocation()
locationManager.stopMonitoringSignificantLocationChanges()
}
// BEST: Modern async API with automatic stationary detection
for try await update in CLLocationUpdate.liveUpdates() {
if update.stationary {
// Device stopped moving — system pauses updates automatically
// Switch to CLMonitor for region monitoring
break
}
handleLocation(update.location)
}
Accuracy comparison (battery impact) :
| Accuracy | Battery Impact | Use Case |
|---|---|---|
kCLLocationAccuracyBest | Very High | Navigation apps only |
kCLLocationAccuracyNearestTenMeters | High | Fitness tracking |
kCLLocationAccuracyHundredMeters | Medium | Store locators |
kCLLocationAccuracyKilometer | Low | Weather apps |
| Significant-change | Very Low | Background updates |
Problem : Background tasks that run too long or too often drain battery.
Your background work must be:
// BAD: Requests unlimited background time
// System will terminate after ~30 seconds anyway
var backgroundTask: UIBackgroundTaskIdentifier = .invalid
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTask = application.beginBackgroundTask {
// Expiration handler — but task runs too long
}
// Long operation that may not complete
performLongOperation()
}
// GOOD: Finish quickly, save progress, notify system
var backgroundTask: UIBackgroundTaskIdentifier = .invalid
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTask = application.beginBackgroundTask(withName: "Save State") { [weak self] in
// Expiration handler — clean up immediately
self?.saveProgress()
if let task = self?.backgroundTask {
application.endBackgroundTask(task)
}
self?.backgroundTask = .invalid
}
// Quick operation
saveEssentialState()
// End task as soon as done — don't wait for expiration
application.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
// BEST: Let system schedule at optimal time (charging, WiFi)
func scheduleBackgroundProcessing() {
let request = BGProcessingTaskRequest(identifier: "com.app.maintenance")
request.requiresNetworkConnectivity = true
request.requiresExternalPower = true // Only when charging
try? BGTaskScheduler.shared.submit(request)
}
// Register handler at app launch
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.app.maintenance",
using: nil
) { task in
self.handleMaintenance(task: task as! BGProcessingTask)
}
// NEW iOS 26: Continue user-initiated tasks with progress UI
let request = BGContinuedProcessingTaskRequest(
identifier: "com.app.export",
title: "Exporting Photos",
subtitle: "23 of 100 photos"
)
try? BGTaskScheduler.shared.submit(request)
Problem : Secondary animations running at higher frame rates than needed increase GPU power.
// BAD: Secondary animation runs at 60fps
// When primary content only needs 30fps, this wastes power
UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat]) {
self.subtitleLabel.alpha = 0.5
} completion: { _ in
self.subtitleLabel.alpha = 1.0
}
// GOOD: Explicitly set preferred frame rate
let displayLink = CADisplayLink(target: self, selector: #selector(updateAnimation))
displayLink.preferredFrameRateRange = CAFrameRateRange(
minimum: 10,
maximum: 30, // Match primary content
preferred: 30
)
displayLink.add(to: .current, forMode: .default)
From WWDC22-10083 : Up to 20% battery savings by aligning secondary animation frame rates with primary content.
waitsForConnectivity set to avoid failed connection attempts?allowsExpensiveNetworkAccess set to false for deferrable work?kCLLocationAccuracyBest unless navigation)?distanceFilter set to reduce update frequency?endBackgroundTask called promptly when work completes?BGProcessingTask with requiresExternalPower?The temptation : "Push notifications are complex. Polling is simpler."
The reality :
Time cost comparison :
Pushback template : "Push notification setup takes a few hours, but polling will guarantee we're at the top of Battery Settings. Users actively uninstall apps that drain battery. The 2-hour investment prevents ongoing reputation damage."
The temptation : "Users expect accurate location. Let's use kCLLocationAccuracyBest."
The reality :
kCLLocationAccuracyBest: GPS + WiFi + Cellular triangulation = massive drainkCLLocationAccuracyHundredMeters: Good enough for 95% of use casesTime cost comparison :
Pushback template : "100-meter accuracy is sufficient for [use case]. Navigation apps like Google Maps need best accuracy, but we're showing [store locations / weather / general area]. The accuracy difference is imperceptible to users, but battery difference is massive."
The temptation : "Animations make the app feel alive and polished."
The reality :
Time cost comparison :
Pushback template : "We can keep the animation, but should pause it when the view isn't visible. This is a 5-minute change that prevents GPU drain when users aren't looking at the screen."
The temptation : "Energy optimization is polish. We can do it in v1.1."
The reality :
Time cost comparison :
Pushback template : "A 15-minute Power Profiler session before launch catches major energy issues. If we ship with battery problems, users will see us at top of Battery Settings on day one and leave 1-star reviews. Let me do a quick check — it's faster than damage control."
Symptom : CPU power impact jumped from 1 to 21 when opening Library pane. UI hung.
Diagnosis using Power Profiler :
VideoCardView body called hundreds of timesVStack creating ALL video thumbnails upfrontFix :
// Before: VStack (eager)
VStack {
ForEach(videos) { video in
VideoCardView(video: video)
}
}
// After: LazyVStack (on-demand)
LazyVStack {
ForEach(videos) { video in
VideoCardView(video: video)
}
}
Result : CPU power impact dropped from 21 to 4.3. UI no longer hung.
Symptom : User commuting reported massive battery drain. Developer couldn't reproduce at desk.
Diagnosis using on-device Power Profiler :
videoSuggestionsForLocation consuming CPUFix :
// Before: Parse on every call
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
let data = try? Data(contentsOf: rulesFileURL)
let rules = try? JSONDecoder().decode([RecommendationRule].self, from: data)
return filteredVideos(using: rules)
}
// After: Parse once, cache
private lazy var cachedRules: [RecommendationRule] = {
let data = try? Data(contentsOf: rulesFileURL)
return (try? JSONDecoder().decode([RecommendationRule].self, from: data)) ?? []
}()
func videoSuggestionsForLocation(_ location: CLLocation) -> [Video] {
return filteredVideos(using: cachedRules)
}
Result : Eliminated CPU spikes during movement. Battery drain resolved.
Symptom : App drains battery even when not playing music.
Diagnosis :
Fix :
// Before: Never deactivate
func playTrack(_ track: Track) {
try? AVAudioSession.sharedInstance().setActive(true)
player.play()
}
func stopPlayback() {
player.stop()
// Audio session still active!
}
// After: Deactivate when done
func stopPlayback() {
player.stop()
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
}
// Even better: Use AVAudioEngine auto-shutdown
let engine = AVAudioEngine()
engine.isAutoShutdownEnabled = true // Automatically powers down when idle
Result : Background audio hardware powered down. Battery drain eliminated.
Detect and adapt when user enables Low Power Mode:
// Check current state
if ProcessInfo.processInfo.isLowPowerModeEnabled {
reduceEnergyUsage()
}
// React to changes
NotificationCenter.default.publisher(for: .NSProcessInfoPowerStateDidChange)
.sink { [weak self] _ in
if ProcessInfo.processInfo.isLowPowerModeEnabled {
self?.reduceEnergyUsage()
} else {
self?.restoreNormalOperation()
}
}
.store(in: &cancellables)
func reduceEnergyUsage() {
// Pause optional activities
// Reduce animation frame rates
// Increase timer intervals
// Defer network requests
// Stop location updates if not critical
}
import MetricKit
class EnergyMetricsManager: NSObject, MXMetricManagerSubscriber {
static let shared = EnergyMetricsManager()
func startMonitoring() {
MXMetricManager.shared.add(self)
}
func didReceive(_ payloads: [MXMetricPayload]) {
for payload in payloads {
if let cpuMetrics = payload.cpuMetrics {
// Monitor CPU time
let foregroundCPU = cpuMetrics.cumulativeCPUTime
logMetric("foreground_cpu", value: foregroundCPU)
}
if let locationMetrics = payload.locationActivityMetrics {
// Monitor location usage
let backgroundLocation = locationMetrics.cumulativeBackgroundLocationTime
logMetric("background_location", value: backgroundLocation)
}
}
}
}
Check Battery Usage pane in Xcode Organizer for field data:
1. Connect device wirelessly
2. Product → Profile → Blank → Add Power Profiler
3. Record 2-3 minutes of usage
4. Identify dominant subsystem (CPU/GPU/Network/Display)
5. Apply targeted fix from patterns above
6. Record again to verify improvement
| Optimization | Potential Savings |
|---|---|
| Dark Mode on OLED | Up to 70% display power |
| Frame rate alignment | Up to 20% GPU power |
| Push vs poll | 100x network efficiency |
| Location accuracy reduction | 50-90% GPS power |
| Timer tolerance | Significant CPU savings |
| Lazy loading | Eliminates startup CPU spikes |
axiom-energy-ref — Complete API reference with all code examplesaxiom-energy-diag — Symptom-based troubleshooting decision treesaxiom-background-processing — Background task mechanics (why tasks don't run)axiom-performance-profiling — General Instruments workflowsaxiom-memory-debugging — Memory leak diagnosis (often related to energy)axiom-networking — Network optimization patternsaxiom-timer-patterns — Timer crash prevention and lifecycle safetyLast Updated : 2025-12-26 Platforms : iOS 26+, iPadOS 26+ Status : Production-ready energy optimization patterns
Weekly Installs
96
Repository
GitHub Stars
601
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykPass
Installed on
opencode80
codex76
claude-code75
gemini-cli73
cursor73
github-copilot70
ESLint迁移到Oxlint完整指南:JavaScript/TypeScript项目性能优化工具
1,600 周安装