电量优化

获取电量

1.导入文件

2.设置监控为true

#import "IOPSKeys.h"
#import "IOPowerSources.h"

-(double) getBatteryLevel{
    // 返回电量信息
    CFTypeRef blob = IOPSCopyPowerSourcesInfo();
    // 返回电量句柄列表数据
    CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
    CFDictionaryRef pSource = NULL;
    const void *psValue;
    // 返回数组大小
    int numOfSources = CFArrayGetCount(sources);
    // 计算大小出错处理
    if (numOfSources == 0) {
        NSLog(@"Error in CFArrayGetCount");
        return -1.0f;
    }

    // 计算所剩电量
    for (int i=0; i<numOfSources; i++) {
        // 返回电源可读信息的字典
        pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
        if (!pSource) {
            NSLog(@"Error in IOPSGetPowerSourceDescription");
            return -1.0f;
        }
        psValue = (CFStringRef) CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

        int curCapacity = 0;
        int maxCapacity = 0;
        double percentage;

        psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
        CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

        psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
        CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

        percentage = ((double) curCapacity / (double) maxCapacity * 100.0f);
        NSLog(@"curCapacity : %d / maxCapacity: %d , percentage: %.1f ", curCapacity, maxCapacity, percentage);
        return percentage;
    }
    return -1.

查看哪个线程耗电高

查看线程中电量使用情况

1.通过线程信息中的threads数组里的线程信息结构体的thread_basic_info里面有一个记录CPU使用百分比的字段cpu_usage

有了这个cpu_usage字段,就可以遍历所有线程,查看哪个线程cpu使用百分比过高

优化cpu耗电问题

1.避免在app处理大量复杂的数据计算,把数据传到服务器去处理

2.对一定要在app处理的复杂计算,通过gcd的dispatch_block_create_with_qos_class方法指定队列的qos为QOS_CLASS_UTILITY,因为他对电量做了优化 -------------------优化cpu耗电问题

优化I/O操作耗电问题

1.使用NSCache方式延时对I/0进行操作

2.类似SDWebImage,先缓存到内存中,后缓存到磁盘中

苹果电量优化最佳实践

1.可以从cpu、设备唤醒、网络、图形、动画、视频、定位、加速度计、陀螺仪、磁力计、蓝牙等考虑

1、https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/index.html

2、https://developer.apple.com/videos/play/wwdc2017/238/

3、https://www.jianshu.com/p/4555704f9696

Last updated

Was this helpful?