如何基于 os_signpost 给关键函数打标并在 Instruments 中自动对比版本差异?

解读

国内中大型 App(电商、社交、金融)普遍把“启动耗时、核心路径耗时”作为版本灰度的硬性指标。面试官抛出本题,想验证三点:

  1. 你是否真的在生产环境用过 os_signpost,而不是只看过文档;
  2. 能否把“埋点-采集-自动化对比”做成 CI 环节,让 QA 不再人工盯 Instruments;
  3. 对 Objective-C 运行时与 Instruments 模板脚本(.tracetemplate、AppleScript、xctrace)的整合能力。

回答时要体现“可落地、可回滚、可灰度”,否则会被认为是“玩具方案”。

知识点

  1. os_signpost 类型与字段限制
    • event:瞬时点;interval-begin/end:成对出现;interval 支持 32 B 内自定义元数据(OSLogPrivacy 需关闭)。
  2. Objective-C 自动注入
    • 利用 attribute((constructor)) 在 dyld 加载期通过 objc_copyClassList 遍历,对指定前缀类的方法做 method-swizzle,插入 signpost 区间。
  3. Instruments 无头采集
    • xctrace 命令行(Xcode 12+ 自带)支持 Launch-Template、Record-Trace、Export-CSV;可配合 xcodebuild archive 在 CI 节点跑。
  4. 差异模型
    • 把 CSV 中“signpost-interval→duration”按“类+方法+signpost-id”聚合成 95th 百分位,再用 Python 脚本环比上一版本 JSON,若回归 >5% 即标记失败。
  5. 国内合规
    • 不上传原始 trace,只上传聚合后的数值;os_log 关闭动态隐私(OS_LOG_PRIVACY_DISABLED=1)避免中文参数被脱敏成 <private>。

答案

步骤一:统一宏,保证 release 也不被裁剪

// SignpostHelper.h
#import <os/signpost.h>
#import <os/log.h>

extern os_log_t g_log;
#define SIGNPOST_INTERVAL_BEGIN(name, id, ...) \
    os_signpost_interval_begin(g_log, id, name, ##__VA_ARGS__)
#define SIGNPOST_INTERVAL_END(name, id, ...) \
    os_signpost_interval_end(g_log, id, name, ##__VA_ARGS__)

// SignpostHelper.m
os_log_t g_log = NULL;
__attribute__((constructor)) void init_signpost(void) {
    g_log = os_log_create("com.company.app", "performance");
}

步骤二:运行时自动插桩(仅对前缀为“Biz”的类)

#import <objc/runtime.h>
#import "SignpostHelper.h"

__attribute__((constructor)) void swizzle_for_signpost(void) {
    if (g_log == NULL) return;
    unsigned int count = 0;
    Class *classes = objc_copyClassList(&count);
    for (unsigned i = 0; i < count; i++) {
        Class cls = classes[i];
        if (!cls || !NSStringFromClass(cls).hasPrefix(@"Biz")) continue;
        unsigned int mCount = 0;
        Method *methods = class_copyMethodList(cls, &mCount);
        for (unsigned j = 0; j < mCount; j++) {
            SEL sel = method_getName(methods[j]);
            NSString *selStr = NSStringFromSelector(sel);
            // 过滤 getter/setter/alloc 等
            if ([selStr hasPrefix:@"set"] || [selStr hasPrefix:@"_"]) continue;
            Method m = methods[j];
            IMP oldImp = method_getImplementation(m);
            IMP newImp = imp_implementationWithBlock(^id(id self, ...){
                // 用指针地址+selector 拼出 64 位 id
                uint64_t sid = (uint64_t)((__bridge void *)self) ^ (uint64_t)sel;
                SIGNPOST_INTERVAL_BEGIN("BizMethod", sid, "cls=%s sel=%s",
                                        class_getName(cls), sel_getName(sel));
                // 调用原实现
                id (*fn)(id, SEL, ...) = (id (*)(id, SEL, ...))oldImp;
                id ret = fn(self, sel, ((char *)&self)+2*sizeof(id));
                SIGNPOST_INTERVAL_END("BizMethod", sid, "");
                return ret;
            });
            method_setImplementation(m, newImp);
        }
        free(methods);
    }
    free(classes);
}

步骤三:CI 无头采样

# .gitlab-ci.yml
variables:
  SCHEME: "AppStore"
  DEVICE: "iPhone 14,OS=16.4"
script:
  - xcodebuild -scheme $SCHEME -destination "platform=iOS Simulator,name=$DEVICE"
    -derivedDataPath build clean build-for-testing
  - xctrace record --template "Logging" --launch --buildProductsPath build/Build/Products/Debug-iphonesimulator/App.app
    --output traces/app_v$CI_COMMIT_SHORT_SHA.trace --time-limit 60s
  - xctrace export --input traces/app_v$CI_COMMIT_SHORT_SHA.trace --output traces/v$CI_COMMIT_SHORT_SHA.csv
  - python3 scripts/perf_regression.py traces/v$CI_COMMIT_SHORT_SHA.csv traces/v$LAST_TAG.csv

步骤四:差异脚本(核心片段)

def load_95th(csv):
    df = pd.read_csv(csv)
    sig = df[df['Signpost Name']=='BizMethod']
    return sig.groupby(['Class','Selector'])['Duration (ns)'].quantile(0.95)

curr = load_95th(sys.argv[1])
last = load_95th(sys.argv[2])
regress = curr > last * 1.05
if regress.any():
    print("REGRESSION:", regress[regress].index.tolist())
    sys.exit(1)

步骤五:版本回滚与灰度

  • 仅当 MR 包含“perf-critical”标签才跑全链路,否则采样 10%;
  • 回归报告自动 @代码提交人,并阻塞 merge;
  • 生产环境关闭 os_log 私有数据,防止用户敏感字段落盘。

拓展思考

  1. 如何降低插桩本身开销?
    • 用 imp_implementationWithBlock 会额外一次 block 调用,可换成汇编 trampoline 或直接写 objc_msgSend 前缀桩,但需处理 arm64 的 ptrauth。
  2. 多线程场景下 signpost id 冲突怎么办?
    • 可把线程 tid 拼进 id:uint64_t sid = ((uint64_t)pthread_mach_thread_np(pthread_self()) << 32) | (uint64_t)sel;
  3. 如果公司还在用 MRC 老库?
    • os_signpost 只在 iOS 12+ 生效,需用 __builtin_available 做运行时隔离;老库可维持 MRC,但 helper 文件单独开 ARC 编译。
  4. 如何与 Swift 混编?
    • Swift 侧用 os_signpost(.begin, …) 即可,但命名要统一;可在 Swift 方法出口再调一次 Objective-C 的辅助函数,保证 trace 落在同一个 log 对象,方便 Instruments 统一过滤。
  5. 国内安卓同事也想横向对比?
    • 把同一套 95th 模型输出成 JSON,安卓用 Jetpack Benchmark 采集主线程消息耗时,复用 Python 差异脚本,实现双端统一卡口。