iOS 使用Instruments工具Time Profiler进行性能优化

  在项目运行时有时候会出现卡顿感,例如tableView滑动出现卡顿,这个时候就需要追踪卡顿的来源,这个时候就用到Instruments中的Time Profiler来进行性能优化。

  1. 先预编译项目(command+i),然后在弹出来的Instruments工具中选择Time Profiler

    1981114-29f67c8628bf7b5c.png
    Instruments面板

  2. 点击开始运行项目,为了测试这个性能我故意在cell里面添加了阻塞性能代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"测试数据%ld",indexPath.row];
    for (int i = 0; i < 1000; i++) {
        [cell addSubview:[UILabel new]];
    }
    return cell;
}
  1. 然后在运行的项目中滑动tableView会发现出现严重的卡顿感

    1981114-67d23ae2b00fc027.png
    Time Profiler

  2. 会发现CPU此刻处于暴增状态,接近占用100%,所以这个时候就需要找出造成CPU消耗这么大的问题所以,在下面的面板中选中Call Tree中的Separate by ThreadHide System Libraries

    1981114-0abd5d56a454b24b.png
    Time Profiler配置

  3. 接下来在线程中找到问题代码,然后双击定位到代码的位置


    1981114-812a95ac4d594a0e.png
    找到问题代码
1981114-e79b60045d5686f4.png
问题代码位置

注意

如果time profiler中看不到方法名只能看到十六进制地址的解决办法
1、设置profilerdebug模式
首先打开Edit Scheme

1981114-dc1d1b0a4953a176.png
打开Edit Scheme

设置 profilerdebug
1981114-bec6e620c3a65a73.png
设置profiler

2、设置Debug Information Format中对应的Debug下为DWARF with dSYM File。和查看crash log文件一样需要使用dSYM文件来解析方法名称,没有这个的话只能显示十六进制的地址。

1981114-04e0b62277ad292d.png
Debug Information Format

Demo下载

猜你喜欢

转载自blog.csdn.net/weixin_33998125/article/details/87554961