如何基于 XCTest 的 measure 编写性能基准测试并集成 CI?

解读

国内 iOS 团队对性能退化 0.1 秒都无法容忍,尤其电商、短视频、金融类 App 直接关联转化率和合规。面试时,面试官想确认三件事:

  1. 你是否真的用过 measure 系列 API,而不是只会 NSLog 打时间戳;
  2. 能否把“测一次”变成“可重复、可对比、可拦截发布流程”的基准测试;
  3. 是否了解 Objective-C Runtime 与 XCTest 的交互细节,能在老代码里插桩而不污染业务。

因此,回答要给出“可落地的工程模板”,并说明如何在 GitLab CI / Jenkins / GitHub Actions 里跑通,最后还要预留灰度容错方案,否则会被追问“线上 Crash 怎么办”。

知识点

  1. XCTest 性能测试分类

    • measureBlock: 最原始,只给均值。
    • measureMetrics:autoStartMeasuringFor:block: 可指定 XCTPerformanceMetric_WallClockTime 等,还能自定义 XCTMetric。
    • measureWithMetrics:automaticallyStartMeasuring:for: 支持并发场景与多指标。
  2. 基准(Baseline)机制

    • 第一次跑会提示“Set Baseline”,写入 .xctestplan 或 .plist;后续跑失败阈值默认 10 %,可在 xcodebuild -testPlan 里用 --performance-test-default-max-standard-deviation 微调。
  3. 稳定性三板斧

    • 预热:在 measure 外先跑 3 次,防止懒加载 + dyld 干扰。
    • 隔离:把待测代码抽到 dynamic 库,防止缓存抖动。
    • 锁频:CI 里用 sudo nvram boot-args="cpus=1" 或 Instruments 的 thermal-state-override 模拟低电量模式,降低硬件波动。
  4. 内存管理陷阱

    • ARC 下 measureBlock 会循环引用 self,需要 __weak typeof(self) wSelf = self;。
    • 若测试 MRC 老库,需手动 autoreleasepool 包住,否则 alloc/release 次数不一致导致基准漂移。
  5. CI 集成要点

    • 用 xcodebuild test-without-building -xctestrun 跑,防止每次重新编译引入噪声。
    • 产物:.xcresult 里 ActionTestPerformanceMetricSummary 可解析 JSON,配合 jq 提取 max 值,推送到内部 Prometheus,超阈值发飞书告警。
    • 失败策略:CI 里加 allow_failure: true,但把结果写回 MR 评论,走“人工二次确认”流程,避免误杀。
  6. Runtime 插桩(加分项)

    • 用 method_exchangeImplementations 把 -[XXXHeavyOperation run] 换成 -[XXXHeavyOperation run_],在 measure 里只测新实现,无需改业务源码,回滚风险 0。

答案

下面给出一个可直接搬进现网 Xcode 13+ 工程的 Objective-C 模板,并附带 GitLab CI 脚本,全部踩过国内私有云 Mac 节点坑。

  1. 测试文件 PerformanceTests.m
#import <XCTest/XCTest.h>
#import "ImageProcessor.h"   // 业务老代码,负责高斯模糊

@interface ImageProcessorTests : XCTestCase
@property (nonatomic, strong) UIImage *sampleImage;
@end

@implementation ImageProcessorTests

- (void)setUp {
    [super setUp];
    // 用 4K 图放大噪声,放大性能差异
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [bundle pathForResource:@"4K" ofType:@"jpg"];
    self.sampleImage = [UIImage imageWithContentsOfFile:path];
    // 预热,防止 CoreGraphics 缓存
    [ImageProcessor gaussianBlur:self.sampleImage radius:10];
}

- (void)testGaussianBlurPerformance {
    // 自定义指标:只看最大一帧,防止毛刺被平均
    XCTMetric *clockMetric = [XCTClockMetric metric];
    [self measureWithMetrics:@[clockMetric] automaticallyStartMeasuring:YES block:^{
        UIImage *out = [ImageProcessor gaussianBlur:self.sampleImage radius:15];
        XCTAssertNotNil(out);
    }];
}

// 若需要 Runtime 插桩,可再加一个 test 方法
- (void)testHookedPerformance {
    Method ori = class_getInstanceMethod([ImageProcessor class], @selector(gaussianBlur:radius:));
    Method swz = class_getInstanceMethod([ImageProcessor class], @selector(gaussianBlur_swizzled:radius:));
    method_exchangeImplementations(ori, swz);

    [self measureBlock:^{
        UIImage *out = [ImageProcessor gaussianBlur:self.sampleImage radius:15];
        XCTAssertEqual(out.size.width, self.sampleImage.size.width);
    }];

    // 换回来,避免污染其他测试
    method_exchangeImplementations(swz, ori);
}
@end
  1. 基准值固化
    本地首次跑完后,Xcode 会弹窗“Set Baseline”。点击确认,值会写进 .xctestplan 文件,一并提交 Git。注意把 *.xctestplan 加入版本控制,否则 CI 找不到基准会报 No baseline found 错误。

  2. GitLab CI .gitlab-ci.yml(macOS 私有 runner)

stages: [performance]

variables:
  DEVELOPER_DIR: /Applications/Xcode13.4.app/Contents/Developer

performance_test:
  stage: performance
  tags: [macos, xcode13]
  script:
    # 1. 编译一次,缓存产物
    - xcodebuild -workspace MyApp.xcworkspace -scheme PerformanceUITests -destination 'platform=iOS Simulator,name=iPhone 13' -derivedDataPath DerivedData clean build-for-testing
    # 2. 跑性能测试,关闭其他测试减少噪声
    - xcodebuild test-without-building -xctestrun DerivedData/Build/Products/*.xctestrun -destination 'platform=iOS Simulator,name=iPhone 13' -only-testing:PerformanceUITests/ImageProcessorTests/testGaussianBlurPerformance -resultBundlePath PerformanceResult
    # 3. 解析结果,推送到内部监控
    - xcrun xcresulttool get --format json --path PerformanceResult | jq '.metrics."testGaussianBlurPerformance".max.time' > maxTime.txt
    - curl -X POST -d "{\"metric\":\"blur_max\",\"value\":$(cat maxTime.txt)}" https://prometheus.xxx.com/report
  allow_failure: true
  artifacts:
    reports:
      junit: PerformanceResult.xcresult
    expire_in: 1 week
  1. 灰度容错
    在 ImageProcessor 里埋“性能开关”:
static BOOL gBlurFallback = NO;
void EnableBlurFallback(BOOL flag) { gBlurFallback = flag; }

当 CI 连续三次基准失败后,自动合并 MR 前调用 EnableBlurFallback(YES),走 CPU 低功耗路径,先保发布,再排障。

拓展思考

  1. 多设备分位值
    国内用户机型碎片化严重,可在 CI 矩阵里加 iPhone 6s(A9)与 iPhone 13(A15),分别设置两套 baseline,用 xcodebuild -destination 并行跑,再按 70 % 低端 + 30 % 高端加权,得出“代表值”。

  2. 自定义 XCTMetric
    如果瓶颈是内存而非 CPU,可继承 XCTMetric 子类,在 copy 方法里返回 [[NSProcessInfo processInfo] physicalMemory] 快照,实现“峰值内存”指标,同样可入 baseline。

  3. 与 Swift 混编
    老工程逐步迁移到 Swift,性能测试仍用 Objective-C 写,通过 @objc 暴露 Swift 类,再用 measure 调用,可保证历史数据连续性;注意 Swift 的 -Owholemodule 优化开关必须与 CI 保持一致,否则 baseline 漂移。

  4. 合规留痕
    金融类 App 需通过央行备案,性能报告作为“软件质量证明材料”上交。CI 里把 .xcresult 原始文件存到 MinIO 对象存储,文件名带 MR 编号,方便审计员下载复现。

  5. 反向基准保护
    除了“跑慢了要报警”,也要防止“跑太快”——优化后均值下降 50 % 可能是算法被短路。可在测试里加 XCTAssertGreaterThan(mean, 0.8 * baseline),防止意外退化到错误分支。