如何让perf data convert输出包含Pharo Smalltalk方法的可解析JSON数据?
解决perf统计Pharo Smalltalk方法耗时并导出含调用链的JSON问题
方法1:解析perf script输出,自定义脚本生成目标JSON
perf report的文本格式难以结构化解析,但perf script能输出更原始、规整的样本数据,我们可以通过脚本聚合这些数据,生成包含Smalltalk方法调用链和耗时占比的JSON。
步骤:
- 导出perf script原始数据:
perf script -i perf.data > perf_script_output.txt
- 编写解析脚本(以Python为例):
脚本会遍历样本、聚合相同调用链的出现次数、计算占比,并转换为目标JSON格式:
import json from collections import defaultdict # 统计各调用链的样本数 call_chain_counts = defaultdict(int) total_samples = 0 with open('perf_script_output.txt', 'r') as f: current_chain = [] for line in f: line = line.strip() if not line: if current_chain: # 反转调用链顺序(从底层到上层转为业务逻辑到底层) reversed_chain = list(reversed(current_chain)) chain_key = tuple(reversed_chain) call_chain_counts[chain_key] += 1 total_samples += 1 current_chain = [] else: # 提取方法名,处理内联标记 if '[.]' in line: symbol_part = line.split('[.]')[1].strip() symbol = symbol_part.replace('(inlined)', '').strip() current_chain.append(symbol) # 生成目标JSON结构 result = [] for chain, count in call_chain_counts.items(): percentage = (count / total_samples) * 100 call_chain_entries = [{'symbol': sym} for sym in chain] result.append({ 'sample_count': count, 'percentage': round(percentage, 2), 'callchain': call_chain_entries }) # 保存JSON文件 with open('pharo_perf_results.json', 'w') as f: json.dump(result, f, indent=2)
- 运行脚本后,
pharo_perf_results.json就包含了各调用链的耗时占比和方法信息。
方法2:编译支持perf map的Pharo VM
Pharo VM默认不会向perf暴露Smalltalk方法符号,通过编译时启用perf map支持,让VM生成perf能识别的动态符号映射文件,这样perf data convert --to-json就能直接包含Smalltalk方法信息。
步骤:
- 获取Pharo VM源码:
git clone https://github.com/pharo-project/pharo-vm.git cd pharo-vm
- 编译时添加
ENABLE_PERF_MAP=1选项:
./build.sh -DENABLE_PERF_MAP=1
- 使用编译好的VM运行Pharo程序,VM会自动在
/tmp目录生成perf-$PID.map文件($PID为Pharo进程ID)。 - 重新执行perf记录和转换:
perf record -g ./path/to/your/pharo-vm/pharo your_image.image perf data convert --to-json -i perf.data > pharo_perf.json
此时生成的JSON文件会直接包含Smalltalk方法的调用链信息。
方法3:结合Pharo内置性能工具(补充方案)
如果不需要完全依赖perf,Pharo自带的MessageTally工具可以直接统计Smalltalk方法的调用耗时,示例代码:
MessageTally spyOn: [ YourClass yourPerformanceTestMethod ]
它会输出结构化的方法耗时统计,你可以直接在Pharo内导出为JSON格式,再结合perf的系统级数据做补充分析。
内容的提问来源于stack exchange,提问作者Matburnx
相关产品推荐
相关产品推荐

