veh*_*zzz 3 c c++ optimization performance
我有这种C函数 - 被称为无数次:
void foo ()
{
if (/*condition*/)
{
}
else if(/*another_condition*/)
{
}
else if (/*another_condition_2*/)
{
}
/*And so on, I have 4 of them, but we can generalize it*/
else
{
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个很好的测试用例调用这个函数,导致某些if-branches被调用比其他的更多.
我的目标是找出安排if语句以最小化分支的最佳方法.
我能想到的唯一方法是为每个if条件分支写入文件,从而创建直方图.这似乎是一种乏味的方式.有更好的方法,更好的工具吗?
我正在使用gcc 3.4在AS3 Linux上构建它; 使用oprofile(opcontrol)进行性能分析.
Chr*_*utz 14
它不可移植,但许多版本的GCC支持一个名为的函数__builtin_expect(),可用于告诉编译器我们期望值是什么:
if(__builtin_expect(condition, 0)) {
// We expect condition to be false (0), so we're less likely to get here
} else {
// We expect to get here more often, so GCC produces better code
}
Run Code Online (Sandbox Code Playgroud)
Linux内核使用它们作为宏来使它们更直观,更清晰,更便携(即重新定义非GCC系统上的宏):
#ifdef __GNUC__
# define likely(x) __builtin_expect((x), 1)
# define unlikely(x) __builtin_expect((x), 0)
#else
# define likely(x) (x)
# define unlikely(x) (x)
#endif
Run Code Online (Sandbox Code Playgroud)
有了这个,我们可以重写上面的内容:
if(unlikely(condition)) {
// we're less likely to get here
} else {
// we expect to get here more often
}
Run Code Online (Sandbox Code Playgroud)
当然,这可能是不必要的,除非你的目标是原始速度和/或你已经分析并发现这是一个问题.
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |