clang(-ftime-trace)优化C/C++工程编译时长
1 编译/安装ClangBuildAnalyzer
clang参数-ftime-trace需要与ClangBuildAnalyzer工具一起工作,输出每个文件的编译时长统计,首先下载ClangBuildAnalyzer:
git clone https://github.com/aras-p/ClangBuildAnalyzer.git
or
git clone https://gitee.com/wangwenchaonj/ClangBuildAnalyzer.git
编译ClangBuildAnalyzer:
cd ClangBuildAnalyzer
make -f projects/make/Makefile
将ClangBuildAnalyzer添加到系统路径:
cd build
cp ClangBuildAnalyzer /usr/local/bin/
aaa@qq.com:/home/~# ClangBuildAnalyzer
USAGE: one of
ClangBuildAnalyzer --start <artifactsdir>
ClangBuildAnalyzer --stop <artifactsdir> <filename>
ClangBuildAnalyzer --analyze <filename>
2 待优化工程参数设置
设置clang编译器:
export CC=/usr/local/bin/clang
export CXX=/usr/local/bin/clang++
设置clang编译器-ftime-trace
参数:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftime-trace")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftime-trace")
3 编译
对ClangBuildAnalyzer源码进行编译:
mkdir build
ClangBuildAnalyzer --start ./build
make -f projects/make/Makefile
ClangBuildAnalyzer --stop ./build/ ClangBuildAnalyzer.data
ClangBuildAnalyzer --analyze ClangBuildAnalyzer.data
ls
chmod -R 777 *
4 Chrome://tracing查看编译时长统计数据
chrome://tracing只支持单个源文件的编译统计的导入,通过python脚本将所有源文件的编译统计汇总,用speedscope或chrome://tracing查看即可该工程的编译统计情况。
#!/usr/bin/env python3
"""Combine JSON from multiple -ftime-traces into one.
Run with (e.g.): python combine_traces.py foo.json bar.json.
"""
import json
import sys
if __name__ == '__main__':
start_time = 0
combined_data = []
for filename in sys.argv[1:]:
with open(filename, 'r') as f:
file_time = None
for event in json.load(f)['traceEvents']:
# Skip metadata events
# Skip total events
# Filter out shorter events to reduce data size
if event['ph'] == 'M' or \
event['name'].startswith('Total') or \
event['dur'] < 5000:
continue
if event['name'] == 'ExecuteCompiler':
# Find how long this compilation takes
file_time = event['dur']
# Set the file name in ExecuteCompiler
event['args']['detail'] = filename
# Offset start time to make compiles sequential
event['ts'] += start_time
# Add data to combined
combined_data.append(event)
# Increase the start time for the next file
# Add 1 to avoid issues with simultaneous events
start_time += file_time + 1
with open('combined.json', 'w') as f:
json.dump({'traceEvents': sorted(combined_data, key=lambda k: k['ts'])}, f)
5 参考链接
https://github.com/aras-p/ClangBuildAnalyzer/tree/v1.2.0
https://www.snsystems.com/technology/tech-blog/clang-time-trace-feature
https://aras-p.info/blog/2019/01/16/time-trace-timeline-flame-chart-profiler-for-Clang/
https://firmwaresecurity.com/2019/11/01/clang-build-analyzer-clang-build-analysis-tool/
https://aras-p.info/blog/2019/09/28/Clang-Build-Analyzer/
https://aras-p.info/blog/2019/01/12/Investigating-compile-times-and-Clang-ftime-report/
https://github.com/jlfwong/speedscope
上一篇: 一千行的MySQL学习笔记汇总
下一篇: WKWebView与JS交互