使用Linux系统工具Perf收集性能事件(分支预测、缓存)和绘制火焰图
原文作者黄崇艺,转载自其博客文章。
Perf
Debian 安装 perf
sudo apt install linux-perf
收集分支预测事件
perf stat -e branch-instructions,branch-misses <your_program>
- branch-instructions:分支指令的总数
- branch-misses:分支预测失败的次数
hit_rate = 1 - branch-misses / branch-instructions //命中率
以下是一个包含多个复杂分支跳转的 C 语言程序示例。这个程序包含了多层嵌套的条件判断、循环和函数调用,以演示复杂的分支逻辑
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 模拟复杂条件的函数
int complex_condition(int x) {
if (x % 2 == 0) {
if (x % 3 == 0) {
return 1; // 可被2和3整除
} else {
if (x % 5 == 0) {
return 2; // 可被2和5整除
} else {
return 3; // 可被2整除,但不能被3或5整除
}
}
} else {
if (x % 7 == 0) {
return 4; // 可被7整除
} else {
return 5; // 不能被2或7整除
}
}
}
// 递归函数,模拟复杂的分支跳转
int recursive_function(int depth) {
if (depth <= 0) {
return 0;
} else {
if (depth % 2 == 0) {
return depth