本文源自本人的學(xué)習(xí)記錄整理與理解,其中參考閱讀了部分優(yōu)秀的博客和書籍背捌,盡量以通俗簡(jiǎn)單的語(yǔ)句轉(zhuǎn)述毙籽。引用到的地方如有遺漏或未能一一列舉原文出處還望見(jiàn)諒與指出,另文章內(nèi)容如有不妥之處還望指教毡庆,萬(wàn)分感謝 坑赡!
性能優(yōu)化是開發(fā)中不可避開的一個(gè)環(huán)節(jié),也是開發(fā)者需要深入研究的一個(gè)課題么抗;提高APP的性能也是一名高級(jí)開發(fā)者的必備技能 毅否!
這里只聊聊關(guān)于iOS系統(tǒng)下的APP性能那些事 !想了解APP的性能就需要知道它體現(xiàn)在那些方面蝇刀,以及如何監(jiān)控它螟加,并優(yōu)化它!
APP的性能大概體現(xiàn)在以下方面:
CPU 占用率
、 內(nèi)存使用情況
捆探、啟動(dòng)時(shí)間
然爆、卡頓
、FPS
黍图、使用時(shí)崩潰率
曾雕、耗電量監(jiān)控
、流量監(jiān)控
助被、網(wǎng)絡(luò)狀況監(jiān)控
剖张、等等。
本文會(huì)從硬件CPU的工作原理揩环,到卡頓和離屏渲染搔弄、到APP的啟動(dòng)、電池的能耗检盼、再到安裝包瘦身肯污;做逐一認(rèn)識(shí)和盡可能的提出優(yōu)化辦法
1. CPU 占用率
CPU
作為中央處理器,是手機(jī)最關(guān)鍵的組成部分吨枉,所有應(yīng)用程序都需要它來(lái)調(diào)度運(yùn)行蹦渣,且資源有限。所以當(dāng)我們的APP因設(shè)計(jì)不當(dāng)
貌亭,使 CPU 持續(xù)以高負(fù)載
運(yùn)行柬唯,將會(huì)出現(xiàn)APP卡頓
、手機(jī)發(fā)熱發(fā)燙
圃庭、電量消耗過(guò)快
等等嚴(yán)重影響用戶體驗(yàn)的現(xiàn)象锄奢。
由此對(duì)于應(yīng)用在CPU中占用率的監(jiān)控,將變得尤為重要剧腻。那么應(yīng)該如何來(lái)獲取CPU的占有率呢拘央?!
我們知道APP在運(yùn)行的時(shí)候书在,會(huì)對(duì)應(yīng)一個(gè)Mach Task
灰伟,而Task
下可能有多條線程同時(shí)執(zhí)行任務(wù),每個(gè)線程都是作為利用CPU的基本單位儒旬。所以我們可以通過(guò)獲取當(dāng)前Mach Task
下所有線程占用 CPU
的情況栏账,來(lái)計(jì)算APP的 CPU 占有率。
在《OS X and iOS Kernel Programming》
是這樣描述 Mach task
的:
任務(wù)
(task)
是一種容器(container)
對(duì)象栈源,虛擬內(nèi)存空間和其他資源都是通過(guò)這個(gè)容器對(duì)象管理的挡爵,這些資源包括設(shè)備和其他句柄。嚴(yán)格地說(shuō)甚垦,Mach
的任務(wù)并不是其他操作系統(tǒng)中所謂的進(jìn)程茶鹃,因?yàn)?Mach
作為一個(gè)微內(nèi)核的操作系統(tǒng)涣雕,并沒(méi)有提供“進(jìn)程”的邏輯,而只是提供了最基本的實(shí)現(xiàn)前计。不過(guò)在BSD
的模型中胞谭,這兩個(gè)概念有1:1的簡(jiǎn)單映射垃杖,每一個(gè)BSD 進(jìn)程
(也就是OS X
進(jìn)程)都在底層關(guān)聯(lián)了一個(gè)Mach
任務(wù)對(duì)象男杈。
iOS 是基于 Apple Darwin
內(nèi)核,由操作系統(tǒng)(kernel)
调俘、XNU內(nèi)核
和Runtime庫(kù)
組成伶棒,而 XNU 是 Darwin 的內(nèi)核,它是“X is not UNIX”的縮寫彩库,是一個(gè)混合內(nèi)核肤无,由 Mach 微內(nèi)核
和BSD
組成。Mach 內(nèi)核是輕量級(jí)的平臺(tái)骇钦,只能完成操作系統(tǒng)最基本的職責(zé)宛渐,比如:進(jìn)程和線程、虛擬內(nèi)存管理眯搭、任務(wù)調(diào)度窥翩、進(jìn)程通信和消息傳遞機(jī)制等。其他的工作鳞仙,例如文件操作和設(shè)備訪問(wèn)寇蚊,都由 BSD
層實(shí)現(xiàn)。
iOS 的線程技術(shù)與Mac OS X
類似棍好,也是基于 Mach 線程技術(shù)實(shí)現(xiàn)的仗岸,在 Mach 層中 thread_basic_info
結(jié)構(gòu)體封裝了單個(gè)線程的基本信息:
struct thread_basic_info {
time_value_t user_time; /* user run time */
time_value_t system_time; /* system run time */
integer_t cpu_usage; /* scaled cpu usage percentage */
policy_t policy; /* scheduling policy in effect */
integer_t run_state; /* run state (see below) */
integer_t flags; /* various flags (see below) */
integer_t suspend_count; /* suspend count for thread */
integer_t sleep_time; /* number of seconds that thread has been sleeping */
}
一個(gè)Mach Task包含它的線程列表。內(nèi)核提供了task_threads
API 調(diào)用獲取指定 task 的線程列表借笙,然后可以通過(guò)thread_info
API調(diào)用來(lái)查詢指定線程的信息扒怖,在thread_act.h
中有相關(guān)定義。
task_threads
將target_task
任務(wù)中的所有線程保存在act_list
數(shù)組中业稼,act_listCnt表示線程個(gè)數(shù):
kern_return_t task_threads
(
task_t target_task,
thread_act_array_t *act_list,
mach_msg_type_number_t *act_listCnt
);
thread_info結(jié)構(gòu)如下:
kern_return_t thread_info
(
thread_act_t target_act,
thread_flavor_t flavor, // 傳入不同的宏定義獲取不同的線程信息
thread_info_t thread_info_out, // 查詢到的線程信息
mach_msg_type_number_t *thread_info_outCnt // 信息的大小
);
所以我們?nèi)缦聛?lái)獲取CPU的占有率:
#import "LSLCpuUsage.h"
#import <mach/task.h>
#import <mach/vm_map.h>
#import <mach/mach_init.h>
#import <mach/thread_act.h>
#import <mach/thread_info.h>
@implementation LSLCpuUsage
+ (double)getCpuUsage {
kern_return_t kr;
thread_array_t threadList; // 保存當(dāng)前Mach task的線程列表
mach_msg_type_number_t threadCount; // 保存當(dāng)前Mach task的線程個(gè)數(shù)
thread_info_data_t threadInfo; // 保存單個(gè)線程的信息列表
mach_msg_type_number_t threadInfoCount; // 保存當(dāng)前線程的信息列表大小
thread_basic_info_t threadBasicInfo; // 線程的基本信息
// 通過(guò)“task_threads”API調(diào)用獲取指定 task 的線程列表
// mach_task_self_盗痒,表示獲取當(dāng)前的 Mach task
kr = task_threads(mach_task_self(), &threadList, &threadCount);
if (kr != KERN_SUCCESS) {
return -1;
}
double cpuUsage = 0;
for (int i = 0; i < threadCount; i++) {
threadInfoCount = THREAD_INFO_MAX;
// 通過(guò)“thread_info”API調(diào)用來(lái)查詢指定線程的信息
// flavor參數(shù)傳的是THREAD_BASIC_INFO,使用這個(gè)類型會(huì)返回線程的基本信息盼忌,
// 定義在 thread_basic_info_t 結(jié)構(gòu)體积糯,包含了用戶和系統(tǒng)的運(yùn)行時(shí)間、運(yùn)行狀態(tài)和調(diào)度優(yōu)先級(jí)等
kr = thread_info(threadList[i], THREAD_BASIC_INFO, (thread_info_t)threadInfo, &threadInfoCount);
if (kr != KERN_SUCCESS) {
return -1;
}
threadBasicInfo = (thread_basic_info_t)threadInfo;
if (!(threadBasicInfo->flags & TH_FLAGS_IDLE)) {
cpuUsage += threadBasicInfo->cpu_usage;
}
}
// 回收內(nèi)存谦纱,防止內(nèi)存泄漏
vm_deallocate(mach_task_self(), (vm_offset_t)threadList, threadCount * sizeof(thread_t));
return cpuUsage / (double)TH_USAGE_SCALE * 100.0;
}
@end
當(dāng)然也可以更直觀的看CPU的占有率看成,用神奇的Xcode
2. 內(nèi)存
雖然現(xiàn)在的手機(jī)內(nèi)存越來(lái)越大,但畢竟是有限的跨嘉,如果因?yàn)槲覀兊膽?yīng)用設(shè)計(jì)不當(dāng)造成內(nèi)存過(guò)高川慌,可能面臨被系統(tǒng)“干掉”的風(fēng)險(xiǎn),這對(duì)用戶來(lái)說(shuō)是毀滅性的體驗(yàn)。
-
Mach task
的內(nèi)存使用信息存放在mach_task_basic_info
結(jié)構(gòu)體中 梦重,其中resident_size
為應(yīng)用使用的物理內(nèi)存大小兑燥,virtual_size
為虛擬內(nèi)存大小,在task_info.h
中:
#define MACH_TASK_BASIC_INFO 20 /* always 64-bit basic info */
struct mach_task_basic_info {
mach_vm_size_t virtual_size; /* virtual memory size (bytes) */
mach_vm_size_t resident_size; /* resident memory size (bytes) */
mach_vm_size_t resident_size_max; /* maximum resident memory size (bytes) */
time_value_t user_time; /* total user run time for
terminated threads */
time_value_t system_time; /* total system run time for
terminated threads */
policy_t policy; /* default policy for new threads */
integer_t suspend_count; /* suspend count for task */
};
獲取方式是通過(guò) task_info
API 根據(jù)指定的 flavor
類型琴拧,返回 target_task
的信息降瞳,在task.h
中:
kern_return_t task_info
(
task_name_t target_task,
task_flavor_t flavor,
task_info_t task_info_out,
mach_msg_type_number_t *task_info_outCnt
);
筆者嘗試過(guò)使用如下方式獲取內(nèi)存情況,基本和騰訊的GT的相近蚓胸,但是和Xcode
和Instruments
的值有較大差距:
// 獲取當(dāng)前應(yīng)用的內(nèi)存占用情況挣饥,和Xcode數(shù)值相差較大
+ (double)getResidentMemory {
struct mach_task_basic_info info;
mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &count) == KERN_SUCCESS) {
return info.resident_size / (1024 * 1024);
} else {
return -1.0;
}
}
后來(lái)看了一篇博主討論了這個(gè)問(wèn)題,說(shuō)使用phys_footprint
才是正解沛膳,博客地址扔枫。親測(cè),基本和Xcode的數(shù)值相近锹安。
// 獲取當(dāng)前應(yīng)用的內(nèi)存占用情況短荐,和Xcode數(shù)值相近
+ (double)getMemoryUsage {
task_vm_info_data_t vmInfo;
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
if(task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vmInfo, &count) == KERN_SUCCESS) {
return (double)vmInfo.phys_footprint / (1024 * 1024);
} else {
return -1.0;
}
}
博主文中提到:關(guān)于 phys_footprint
的定義可以在 XNU 源碼中,找到 osfmk/kern/task.c
里對(duì)于 phys_footprint
的注釋叹哭,博主認(rèn)為注釋里提到的公式計(jì)算的應(yīng)該才是應(yīng)用實(shí)際使用的物理內(nèi)存忍宋。
/*
* phys_footprint
* Physical footprint: This is the sum of:
* + (internal - alternate_accounting)
* + (internal_compressed - alternate_accounting_compressed)
* + iokit_mapped
* + purgeable_nonvolatile
* + purgeable_nonvolatile_compressed
* + page_table
*
* internal
* The task's anonymous memory, which on iOS is always resident.
*
* internal_compressed
* Amount of this task's internal memory which is held by the compressor.
* Such memory is no longer actually resident for the task [i.e., resident in its pmap],
* and could be either decompressed back into memory, or paged out to storage, depending
* on our implementation.
*
* iokit_mapped
* IOKit mappings: The total size of all IOKit mappings in this task, regardless of
clean/dirty or internal/external state].
*
* alternate_accounting
* The number of internal dirty pages which are part of IOKit mappings. By definition, these pages
* are counted in both internal *and* iokit_mapped, so we must subtract them from the total to avoid
* double counting.
*/
當(dāng)然我也是贊同這點(diǎn)的????????????。
3. FPS
通過(guò)維基百科我們知道话速,FPS
是Frames Per Second
的簡(jiǎn)稱縮寫讶踪,意思是每秒傳輸幀數(shù),也就是我們常說(shuō)的“刷新率(單位為Hz)泊交。
FPS
是測(cè)量用于保存乳讥、顯示動(dòng)態(tài)視頻的信息數(shù)量。每秒鐘幀數(shù)愈多廓俭,所顯示的畫面就會(huì)愈流暢云石,FPS
值越低就越卡頓
,所以這個(gè)值在一定程度上可以衡量應(yīng)用在圖像繪制渲染處理時(shí)的性能研乒。一般我們的APP的FPS
只要保持在50-60之間
汹忠,用戶體驗(yàn)都是比較流暢
的。
蘋果手機(jī)屏幕的正常刷新頻率是每秒60次雹熬,即可以理解為FPS值為60宽菜。我們都知道CADisplayLink
是和屏幕刷新頻率保存一致,所以我們是否可以通過(guò)它來(lái)監(jiān)控我們的FPS呢竿报?铅乡!
首先CADisplayLink是什么
CADisplayLink
是CoreAnimation
提供的另一個(gè)類似于NSTimer的類,它總是在屏幕完成一次更新之前啟動(dòng)烈菌,它的接口設(shè)計(jì)的和NSTimer很類似阵幸,所以它實(shí)際上就是一個(gè)內(nèi)置實(shí)現(xiàn)的替代花履,但是和timeInterval
以秒為單位不同,CADisplayLink
有一個(gè)整型的frameInterval
屬性挚赊,指定了間隔多少幀之后才執(zhí)行诡壁。默認(rèn)值是1,意味著每次屏幕更新之前都會(huì)執(zhí)行一次荠割。但是如果動(dòng)畫的代碼執(zhí)行起來(lái)超過(guò)了六十分之一秒妹卿,你可以指定frameInterval
為2,就是說(shuō)動(dòng)畫每隔一幀執(zhí)行一次(一秒鐘30幀)涨共。
使用CADisplayLink
監(jiān)控界面的FPS
值纽帖,參考自YYFPSLabel:
import UIKit
class LSLFPSMonitor: UILabel {
private var link: CADisplayLink = CADisplayLink.init()
private var count: NSInteger = 0
private var lastTime: TimeInterval = 0.0
private var fpsColor: UIColor = UIColor.green
public var fps: Double = 0.0
// MARK: - init
override init(frame: CGRect) {
var f = frame
if f.size == CGSize.zero {
f.size = CGSize(width: 55.0, height: 22.0)
}
super.init(frame: f)
self.textColor = UIColor.white
self.textAlignment = .center
self.font = UIFont.init(name: "Menlo", size: 12.0)
self.backgroundColor = UIColor.black
link = CADisplayLink.init(target: LSLWeakProxy(target: self), selector: #selector(tick))
link.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
deinit {
link.invalidate()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - actions
@objc func tick(link: CADisplayLink) {
guard lastTime != 0 else {
lastTime = link.timestamp
return
}
count += 1
let delta = link.timestamp - lastTime
guard delta >= 1.0 else {
return
}
lastTime = link.timestamp
fps = Double(count) / delta
let fpsText = "\(String.init(format: "%.3f", fps)) FPS"
count = 0
let attrMStr = NSMutableAttributedString(attributedString: NSAttributedString(string: fpsText))
if fps > 55.0{
fpsColor = UIColor.green
} else if(fps >= 50.0 && fps <= 55.0) {
fpsColor = UIColor.yellow
} else {
fpsColor = UIColor.red
}
attrMStr.setAttributes([NSAttributedStringKey.foregroundColor:fpsColor], range: NSMakeRange(0, attrMStr.length - 3))
attrMStr.setAttributes([NSAttributedStringKey.foregroundColor:UIColor.white], range: NSMakeRange(attrMStr.length - 3, 3))
DispatchQueue.main.async {
self.attributedText = attrMStr
}
}
}
通過(guò)CADisplayLink
的實(shí)現(xiàn)方式宠漩,并真機(jī)測(cè)試之后举反,確實(shí)是可以在很大程度上滿足了監(jiān)控FPS
的業(yè)務(wù)需求和為提高用戶體驗(yàn)提供參考,但是和Instruments
的值可能會(huì)有些出入扒吁。下面我們來(lái)討論下使用CADisplayLink
的方式火鼻,可能存在的問(wèn)題。
- (1). 和Instruments值對(duì)比有出入雕崩,原因如下:
CADisplayLink
運(yùn)行在被添加的那個(gè)RunLoop
之中(一般是在主線程中)魁索,因此它只能檢測(cè)出當(dāng)前RunLoop
下的幀率。RunLoop
中所管理的任務(wù)的調(diào)度時(shí)機(jī)盼铁,受任務(wù)所處的RunLoopMode
和CPU
的繁忙程度所影響粗蔚。所以想要真正定位到準(zhǔn)確的性能問(wèn)題所在,最好還是通過(guò)Instrument
來(lái)確認(rèn)饶火。
- (2). 使用CADisplayLink可能存在的循環(huán)引用問(wèn)題鹏控。
例如以下寫法:
let link = CADisplayLink.init(target: self, selector: #selector(tick))
let timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
原因:以上兩種用法,都會(huì)對(duì) self 強(qiáng)引用肤寝,此時(shí) timer持有 self当辐,self 也持有 timer,循環(huán)引用導(dǎo)致頁(yè)面 dismiss 時(shí)鲤看,雙方都無(wú)法釋放缘揪,造成循環(huán)引用。此時(shí)使用 weak 也不能有效解決:
weak var weakSelf = self
let link = CADisplayLink.init(target: weakSelf, selector: #selector(tick))
那么我們應(yīng)該怎樣解決這個(gè)問(wèn)題义桂,有人會(huì)說(shuō)在deinit(或dealloc)中調(diào)用定時(shí)器的invalidate方法找筝,但是這是無(wú)效的,因?yàn)橐呀?jīng)造成循環(huán)引用了慷吊,不會(huì)走到這個(gè)方法的袖裕。
YYKit
作者提供的解決方案是使用 YYWeakProxy,這個(gè)YYWeakProxy
不是繼承自NSObject
而是繼承NSProxy
罢浇。
NSProxy
An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet.
NSProxy
是一個(gè)為對(duì)象定義接口的抽象父類陆赋,并且為其它對(duì)象或者一些不存在的對(duì)象扮演了替身角色沐祷。具體的可以看下NSProxy的官方文檔
萬(wàn)能替身上線
修改后代碼如下,親測(cè)定時(shí)器如愿釋放攒岛,LSLWeakProxy
的具體實(shí)現(xiàn)代碼已經(jīng)同步到github中赖临。
let link = CADisplayLink.init(target: LSLWeakProxy(target: self), selector: #selector(tick))
4. CPU和GPU
在屏幕成像的過(guò)程中,CPU和GPU起著至關(guān)重要的作用
**CPU (Central Processing Unit
)
- 對(duì)象的創(chuàng)建和銷毀灾锯、對(duì)象屬性的調(diào)整兢榨、布局計(jì)算、文本的計(jì)算的排版顺饮、圖片的格式轉(zhuǎn)換和解碼吵聪、圖像的繪制 (Core Graphics)
GPU (Graphics Processing Unit
) 圖像處理器
- 紋理的渲染
- 紋理是一個(gè)用來(lái)保存圖像顏色的元素值的緩存,渲染是指將數(shù)據(jù)生成圖像的過(guò)程兼雄。紋理渲染則是將保存在內(nèi)存中的顏色值等數(shù)據(jù)吟逝,生成圖像的過(guò)程。
現(xiàn)在的手機(jī)設(shè)備基本都是采用雙緩存+垂直同步(即V-Sync)屏幕顯示技術(shù)赦肋。
屏幕顯示內(nèi)容的過(guò)程
如上圖所示块攒,系統(tǒng)內(nèi)CPU
、GPU
和顯示器
是協(xié)同完成顯示工作的佃乘。其中CPU負(fù)責(zé)計(jì)算顯示的內(nèi)容囱井,例如視圖創(chuàng)建
、布局計(jì)算
趣避、圖片解碼
庞呕、文本繪制
等等。
隨后CPU將計(jì)算好的內(nèi)容提交給GPU程帕,由GPU進(jìn)行變換住练、合成、渲染骆捧。
GPU會(huì)預(yù)先渲染好一幀放入一個(gè)緩沖區(qū)內(nèi)澎羞,讓視頻控制器讀取,當(dāng)下一幀渲染好后敛苇,GPU會(huì)直接將視頻控制器的指針指向第二個(gè)容器(雙緩存原理)妆绞。這里,GPU會(huì)等待顯示器的VSync(即垂直同步)信號(hào)發(fā)出后枫攀,才進(jìn)行新的一幀渲染和緩沖區(qū)更新(這樣能解決畫面撕裂現(xiàn)象括饶,也增加了畫面流暢度,但需要消費(fèi)更多的計(jì)算資源来涨,也會(huì)帶來(lái)部分延遲)图焰。
離屏渲染
在OpenGL中,GPU有2種渲染方式
On-Screen Rendering
: 當(dāng)前屏幕渲染蹦掐,在當(dāng)前屏幕用于顯示的屏幕緩沖區(qū)進(jìn)行渲染操作Off-Screen Rendering
: 離屏渲染技羔,在當(dāng)前屏幕緩沖區(qū)以外新開辟一個(gè)緩沖區(qū)進(jìn)行渲染操作僵闯;這個(gè)操作是非常消耗性能的離屏渲染消耗性能的原因
- 需要?jiǎng)?chuàng)建新的緩沖區(qū)
- 離屏渲染的整個(gè)過(guò)程,需要多次切換上下文環(huán)境, 先是從當(dāng)前屏幕(
On - Screen
)切換到離屏(Off-Screen
); 等到離屏渲染結(jié)束以后藤滥,將離屏緩沖區(qū)的渲染結(jié)果顯示到屏幕上時(shí)鳖粟,又需要將上下文環(huán)境
從離屏切換到當(dāng)前屏幕
- 那些操作會(huì)觸發(fā)離屏渲染?
- 光柵化拙绊,是將幾何數(shù)據(jù)經(jīng)過(guò)一系列變換后最終轉(zhuǎn)換為像素向图,從而呈現(xiàn)在顯示設(shè)備上 的過(guò)程,光柵化的本質(zhì)是坐標(biāo)變換标沪、幾何離散化榄攀;
- 我們使用 UITableView 和 UICollectionView 時(shí)經(jīng)常會(huì)遇到各個(gè) Cell 的樣式是一 樣的,這時(shí)候我們可以使用這個(gè)屬性提高性能:
layer.shouldRasterize =YES
layer.rasterizationScale = [[UIScreen mainScreen] scale]
- 遮罩金句,layer.mask
- 圓角檩赢,同時(shí)設(shè)置layer.masksToBounds =
YES
、layer.cornerRadius大于0
圓角可以通過(guò)CoreGraphics這種技術(shù)繪制裁剪圓角趴梢,如果是固定圖片可以讓UI提供帶圓角圖片 - 陰影漠畜,layer.shadow相關(guān)API ; 但如果設(shè)置了layer.shadowPath就不會(huì)產(chǎn)生離屏渲染
5. 卡頓
卡頓的原因:
由上面屏幕顯示的原理,采用了垂直同步機(jī)制的手機(jī)設(shè)備坞靶。如果在一個(gè)VSync 時(shí)間內(nèi),CPU 或GPU 沒(méi)有完成內(nèi)容提交蝴悉,則那一幀就會(huì)被丟棄彰阴,等待下一次機(jī)會(huì)再顯示,而這時(shí)顯示屏?xí)A糁暗膬?nèi)容不變拍冠。例如在主線程里添加了阻礙主線程去響應(yīng)點(diǎn)擊尿这、滑動(dòng)事件、以及阻礙主線程的UI繪制等的代碼庆杜,都是造成卡頓的常見(jiàn)原因射众。
卡頓監(jiān)控:
卡頓監(jiān)控一般有兩種實(shí)現(xiàn)方案:
(1). 主線程卡頓監(jiān)控。通過(guò)子線程監(jiān)測(cè)主線程的
runLoop
晃财,判斷結(jié)束休眠
到再次休眠
兩個(gè)狀態(tài)區(qū)域之間的耗時(shí)是否達(dá)到一定閾值叨橱。(2).
FPS
監(jiān)控。要保持流暢的UI交互断盛,App 刷新率應(yīng)該當(dāng)努力保持在 60fps罗洗。FPS
的監(jiān)控實(shí)現(xiàn)原理,上面已經(jīng)探討過(guò)這里略過(guò)钢猛。
在使用FPS監(jiān)控性能的實(shí)踐過(guò)程中伙菜,發(fā)現(xiàn) FPS 值抖動(dòng)較大
,造成偵測(cè)卡頓比較困難命迈。為了解決這個(gè)問(wèn)題贩绕,通過(guò)采用檢測(cè)主線程每次執(zhí)行消息循環(huán)的時(shí)間火的,當(dāng)這一時(shí)間大于規(guī)定的閾值時(shí),就記為發(fā)生了一次卡頓的方式來(lái)監(jiān)控淑倾。
這也是美團(tuán)的移動(dòng)端采用的性能監(jiān)控Hertz 方案卫玖,微信團(tuán)隊(duì)也在實(shí)踐過(guò)程中提出來(lái)類似的方案--微信讀書 iOS 性能優(yōu)化總結(jié)。
/* Run Loop Observer Activities */
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0), // 即將進(jìn)入Loop
kCFRunLoopBeforeTimers = (1UL << 1), // 即將處理Timer
kCFRunLoopBeforeSources = (1UL << 2), // 即將處理Source
kCFRunLoopBeforeWaiting = (1UL << 5), // 即將進(jìn)入休眠
kCFRunLoopAfterWaiting = (1UL << 6), // 剛從休眠中喚醒
kCFRunLoopExit = (1UL << 7), // 即將退出Loop
kCFRunLoopAllActivities = 0x0FFFFFFFU // 所有狀態(tài)
};
方案的提出踊淳,是根據(jù)滾動(dòng)引發(fā)的Sources事件
或其它交互事件總是被快速的執(zhí)行完成假瞬,然后進(jìn)入到kCFRunLoopBeforeWaiting
狀態(tài)下;假如在滾動(dòng)過(guò)程中發(fā)生了卡頓現(xiàn)象迂尝,那么RunLoop必然會(huì)保持kCFRunLoopAfterWaiting
或者kCFRunLoopBeforeSources
這兩個(gè)狀態(tài)之一脱茉。
所以監(jiān)控主線程卡頓的方案一:
開辟一個(gè)子線程,然后實(shí)時(shí)計(jì)算 kCFRunLoopBeforeSources
和 kCFRunLoopAfterWaiting
兩個(gè)狀態(tài)區(qū)域之間的耗時(shí)是否超過(guò)某個(gè)閥值垄开,來(lái)斷定主線程的卡頓情況琴许。
(南梔傾寒)給出了自己的解決方案,Swift
的卡頓檢測(cè)第三方ANREye溉躲。這套卡頓監(jiān)控方案大致思路為:創(chuàng)建一個(gè)子線程進(jìn)行循環(huán)檢測(cè)榜田,每次檢測(cè)時(shí)設(shè)置標(biāo)記位為YES
,然后派發(fā)任務(wù)到主線程中將標(biāo)記位設(shè)置為NO
锻梳。接著子線程沉睡超時(shí)闕值時(shí)長(zhǎng)箭券,判斷標(biāo)志位是否成功設(shè)置成NO
,如果沒(méi)有說(shuō)明主線程發(fā)生了卡頓疑枯。
結(jié)合這套方案辩块,當(dāng)主線程處在Before Waiting狀態(tài)的時(shí)候,通過(guò)派發(fā)任務(wù)到主線程來(lái)設(shè)置標(biāo)記位的方式處理常態(tài)下的卡頓檢測(cè):
#define lsl_SEMAPHORE_SUCCESS 0
static BOOL lsl_is_monitoring = NO;
static dispatch_semaphore_t lsl_semaphore;
static NSTimeInterval lsl_time_out_interval = 0.05;
@implementation LSLAppFluencyMonitor
static inline dispatch_queue_t __lsl_fluecy_monitor_queue() {
static dispatch_queue_t lsl_fluecy_monitor_queue;
static dispatch_once_t once;
dispatch_once(&once, ^{
lsl_fluecy_monitor_queue = dispatch_queue_create("com.dream.lsl_monitor_queue", NULL);
});
return lsl_fluecy_monitor_queue;
}
static inline void __lsl_monitor_init() {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
lsl_semaphore = dispatch_semaphore_create(0);
});
}
#pragma mark - Public
+ (instancetype)monitor {
return [LSLAppFluencyMonitor new];
}
- (void)startMonitoring {
if (lsl_is_monitoring) { return; }
lsl_is_monitoring = YES;
__lsl_monitor_init();
dispatch_async(__lsl_fluecy_monitor_queue(), ^{
while (lsl_is_monitoring) {
__block BOOL timeOut = YES;
dispatch_async(dispatch_get_main_queue(), ^{
timeOut = NO;
dispatch_semaphore_signal(lsl_semaphore);
});
[NSThread sleepForTimeInterval: lsl_time_out_interval];
if (timeOut) {
[LSLBacktraceLogger lsl_logMain]; // 打印主線程調(diào)用棧
// [LSLBacktraceLogger lsl_logCurrent]; // 打印當(dāng)前線程的調(diào)用棧
// [LSLBacktraceLogger lsl_logAllThread]; // 打印所有線程的調(diào)用棧
}
dispatch_wait(lsl_semaphore, DISPATCH_TIME_FOREVER);
}
});
}
- (void)stopMonitoring {
if (!lsl_is_monitoring) { return; }
lsl_is_monitoring = NO;
}
@end
其中LSLBacktraceLogger
是獲取堆棧信息的類荆永,詳情見(jiàn)代碼Github废亭。
打印日志如下:
2018-08-16 12:36:33.910491+0800 AppPerformance[4802:171145] Backtrace of Thread 771:
======================================================================================
libsystem_kernel.dylib 0x10d089bce __semwait_signal + 10
libsystem_c.dylib 0x10ce55d10 usleep + 53
AppPerformance 0x108b8b478 $S14AppPerformance25LSLFPSTableViewControllerC05tableD0_12cellForRowAtSo07UITableD4CellCSo0kD0C_10Foundation9IndexPathVtF + 1144
AppPerformance 0x108b8b60b $S14AppPerformance25LSLFPSTableViewControllerC05tableD0_12cellForRowAtSo07UITableD4CellCSo0kD0C_10Foundation9IndexPathVtFTo + 155
UIKitCore 0x1135b104f -[_UIFilteredDataSource tableView:cellForRowAtIndexPath:] + 95
UIKitCore 0x1131ed34d -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 765
UIKitCore 0x1131ed8da -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 73
UIKitCore 0x1131b4b1e -[UITableView _updateVisibleCellsNow:isRecursive:] + 2863
UIKitCore 0x1131d57eb -[UITableView layoutSubviews] + 165
UIKitCore 0x1133921ee -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1501
QuartzCore 0x10ab72eb1 -[CALayer layoutSublayers] + 175
QuartzCore 0x10ab77d8b _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 395
QuartzCore 0x10aaf3b45 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 349
QuartzCore 0x10ab285b0 _ZN2CA11Transaction6commitEv + 576
QuartzCore 0x10ab29374 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 76
CoreFoundation 0x109dc3757 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
CoreFoundation 0x109dbdbde __CFRunLoopDoObservers + 430
CoreFoundation 0x109dbe271 __CFRunLoopRun + 1537
CoreFoundation 0x109dbd931 CFRunLoopRunSpecific + 625
GraphicsServices 0x10f5981b5 GSEventRunModal + 62
UIKitCore 0x112c812ce UIApplicationMain + 140
AppPerformance 0x108b8c1f0 main + 224
libdyld.dylib 0x10cd4dc9d start + 1
======================================================================================
方案二: 是結(jié)合CADisplayLink
的方式實(shí)現(xiàn)
在檢測(cè)FPS值的時(shí)候,我們就詳細(xì)介紹了CADisplayLink
的使用方式具钥,在這里也可以通過(guò)FPS值是否連續(xù)低于某個(gè)值開進(jìn)行監(jiān)控豆村。
卡頓解決的主要思路
- 盡可能減少CPU、GPU資源消耗
- 按照60FPS的刷幀率骂删,每隔16ms就會(huì)有一次
VSync
信號(hào)掌动;
也就是說(shuō)在16毫秒內(nèi)完成CPU和GPU的操作就不會(huì)出現(xiàn)卡頓; (1秒鐘等于1000毫秒,1000?60 就等于16.666666666667)
優(yōu)化CPU
- 盡量用輕量級(jí)的對(duì)象桃漾,比如用不到事件處理的地方坏匪,可以考慮使用
CALayer
取代UIView
- 不要頻繁的調(diào)用UIView的相關(guān)屬性,比如frame撬统、bounds适滓、transform等屬性,盡量減少不必要的修改恋追;
- 盡量提前計(jì)算好布局凭迹,在有需要時(shí)一次性調(diào)整對(duì)應(yīng)的屬性罚屋,不要多次修改屬性
-Autolayout
會(huì)比直接設(shè)置frame消耗更多的CPU資源 - 圖片的
size
最好跟UIImageView
的size
保持一致,這樣就不需要拉伸重繪 - 控制一下線程的最大并發(fā)數(shù)量嗅绸,不要開啟一些不必要的線程
- 盡量把耗時(shí)的操作放在子線程脾猛,比如:
文本處理
(尺寸計(jì)算、繪制)鱼鸠、圖片處理
(編碼解碼猛拴、繪制)
圖片解碼可以考慮先獲取CGImage,再創(chuàng)建位圖上下文蚀狰,把圖形數(shù)據(jù)繪制到上面愉昆,這個(gè)過(guò)程就是解碼;最終把CGImage通過(guò)[UIImage imageWithCGImage: CGImage]
轉(zhuǎn)為圖片賦值給UIImageView
主要功能代碼
// context
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, CGColorSpaceCreateDeviceRGB(), bitmapInfo);
// draw
CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
// get CGImage
cgImage = CGBitmapContextCreateImage(context);
// into UIImage
UIImage *newImage = [UIImage imageWithCGImage:cgImage];
類似的實(shí)現(xiàn)在SDWebImage
的SDWebImageImageIOCoder.m
文件的sd_decompressedAndScaledDownImageWithImage:
有用到
- (nullable UIImage *)sd_decompressedAndScaledDownImageWithImage:(nullable UIImage *)image {
CGContextRef destContext;
// autorelease the bitmap context and all vars to help system to free memory when there are memory warning.
// on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory];
@autoreleasepool {
CGImageRef sourceImageRef = image.CGImage;
CGSize sourceResolution = CGSizeZero;
sourceResolution.width = CGImageGetWidth(sourceImageRef);
sourceResolution.height = CGImageGetHeight(sourceImageRef);
float sourceTotalPixels = sourceResolution.width * sourceResolution.height;
// Determine the scale ratio to apply to the input image
// that results in an output image of the defined size.
// see kDestImageSizeMB, and how it relates to destTotalPixels.
float imageScale = kDestTotalPixels / sourceTotalPixels;
CGSize destResolution = CGSizeZero;
destResolution.width = (int)(sourceResolution.width*imageScale);
destResolution.height = (int)(sourceResolution.height*imageScale);
// device color space
CGColorSpaceRef colorspaceRef = SDCGColorSpaceGetDeviceRGB();
BOOL hasAlpha = SDCGImageRefContainsAlpha(sourceImageRef);
// iOS display alpha info (BGRA8888/BGRX8888)
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
// kCGImageAlphaNone is not supported in CGBitmapContextCreate.
// Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
// to create bitmap graphics contexts without alpha info.
destContext = CGBitmapContextCreate(NULL,
destResolution.width,
destResolution.height,
kBitsPerComponent,
0,
colorspaceRef,
bitmapInfo);
if (destContext == NULL) {
return image;
}
CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh);
// Now define the size of the rectangle to be used for the
// incremental blits from the input image to the output image.
// we use a source tile width equal to the width of the source
// image due to the way that iOS retrieves image data from disk.
// iOS must decode an image from disk in full width 'bands', even
// if current graphics context is clipped to a subrect within that
// band. Therefore we fully utilize all of the pixel data that results
// from a decoding opertion by achnoring our tile size to the full
// width of the input image.
CGRect sourceTile = CGRectZero;
sourceTile.size.width = sourceResolution.width;
// The source tile height is dynamic. Since we specified the size
// of the source tile in MB, see how many rows of pixels high it
// can be given the input image width.
sourceTile.size.height = (int)(kTileTotalPixels / sourceTile.size.width );
sourceTile.origin.x = 0.0f;
// The output tile is the same proportions as the input tile, but
// scaled to image scale.
CGRect destTile;
destTile.size.width = destResolution.width;
destTile.size.height = sourceTile.size.height * imageScale;
destTile.origin.x = 0.0f;
// The source seem overlap is proportionate to the destination seem overlap.
// this is the amount of pixels to overlap each tile as we assemble the ouput image.
float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height);
CGImageRef sourceTileImageRef;
// calculate the number of read/write operations required to assemble the
// output image.
int iterations = (int)( sourceResolution.height / sourceTile.size.height );
// If tile height doesn't divide the image height evenly, add another iteration
// to account for the remaining pixels.
int remainder = (int)sourceResolution.height % (int)sourceTile.size.height;
if(remainder) {
iterations++;
}
// Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations.
float sourceTileHeightMinusOverlap = sourceTile.size.height;
sourceTile.size.height += sourceSeemOverlap;
destTile.size.height += kDestSeemOverlap;
for( int y = 0; y < iterations; ++y ) {
@autoreleasepool {
sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap;
destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap);
sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile );
if( y == iterations - 1 && remainder ) {
float dify = destTile.size.height;
destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale;
dify -= destTile.size.height;
destTile.origin.y += dify;
}
CGContextDrawImage( destContext, destTile, sourceTileImageRef );
CGImageRelease( sourceTileImageRef );
}
}
CGImageRef destImageRef = CGBitmapContextCreateImage(destContext);
CGContextRelease(destContext);
if (destImageRef == NULL) {
return image;
}
UIImage *destImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(destImageRef);
if (destImage == nil) {
return image;
}
return destImage;
}
}
優(yōu)化GPU
- 盡量避免短時(shí)間內(nèi)大量圖片的顯示麻蹋,盡可能將多張圖片合成一張進(jìn)行顯示(每張圖都是大圖就算了)
- GPU能處理的最大紋理尺寸是
4096x4096
跛溉,一旦超過(guò)這個(gè)尺寸,就需要更多的時(shí)間處理扮授,這樣CPU的處理空間就會(huì)變小芳室,所以紋理盡量不要超過(guò)這個(gè)尺寸 - 盡量減少視圖數(shù)量和層次
- 減少透明的視圖(
alpha<1
),不透明的就設(shè)置opaque
屬性為YES
;
opaque: 確定視圖是否透明的布爾值 - 盡量避免出現(xiàn)離屏渲染
更多相關(guān)內(nèi)容:啟動(dòng)時(shí)間
、耗電量監(jiān)控
刹勃、使用時(shí)崩潰率
堪侯、流量監(jiān)控
、網(wǎng)絡(luò)狀況監(jiān)控
深夯、等等抖格。,由于篇幅太長(zhǎng)咕晋,將作為第二篇文中發(fā)出,歡迎交流探討收奔。
iOS 底層 - 性能優(yōu)化之啟動(dòng)和電池能耗
iOS 底層 - 性能優(yōu)化之安裝包瘦身(App Thinning)
參考文章: