假设我有一个主循环,每帧更新不同的内容:
int currentFrame = frame % n;
if ( currentFrame == 0 )
{
someVar = frame;
}
else if ( currentFrame == 1 )
{
someOtherVar = x;
}
...
else if ( currentFrame == n - 1 )
{
someMethod();
}
我可以使它对分支预测器更友好吗?分支预测器能否确定每个块将在每个n
帧执行一次?是否有分支无关的替代方案(怀疑,假设块中有足够不同的逻辑)?
请注意,将完全优化,switch
不会有太大的区别(如果有的话)。
正如我在上面评论的那样,没有任何代码示例,我想在这里很难提供任何有用的帮助。你能张贴一个代码片段,显示大量的分支错过?
我刚刚试了这样做:
#include <cstdlib>
__attribute__ ((noinline)) void frame(const int frame) // to prevent automatic unrolling
{
const int n = 10;
static int someVar = rand();
static int someOtherVar = rand();
const int currentFrame = frame % n;
if (currentFrame == 0) {
someVar = frame;
} else if (currentFrame == 1) {
someOtherVar += frame;
} else if (currentFrame == 2) {
someOtherVar -= someOtherVar;
someVar = someOtherVar;
} else if (currentFrame == 3) {
someVar -= someOtherVar;
} else if (currentFrame == 4) {
someVar -= someOtherVar;
someOtherVar *= someOtherVar;
} else if (currentFrame == 5) {
someOtherVar /= someVar + frame;
} else if (currentFrame == 6) {
someVar *= someOtherVar - frame;
} else if (currentFrame == 7) {
someOtherVar += someVar / (someOtherVar + 1);
} else if (currentFrame == 8) {
someVar -= someOtherVar * someVar;
} else if (currentFrame == n - 1) {
someOtherVar = frame;
someVar = frame + 1;
}
}
int main(int argc, char** argv)
{
int iterations = 100000000;
if (argc > 1) {
iterations = std::atoi(argv[1]);
}
for (int i = 0; i < iterations; ++i) {
frame(i);
}
return 0;
}
但这并不能再现你的发现:
Performance counter stats for './a.out 100000000':
591.088374 task-clock (msec) # 0.999 CPUs utilized
60 context-switches # 0.102 K/sec
5 cpu-migrations # 0.008 K/sec
272 page-faults # 0.460 K/sec
1,665,803,234 cycles # 2.818 GHz [50.25%]
<not supported> stalled-cycles-frontend
<not supported> stalled-cycles-backend
3,741,605,478 instructions # 2.25 insns per cycle [75.14%]
1,050,201,459 branches # 1776.725 M/sec [75.14%]
11,115 branch-misses # 0.00% of all branches [74.64%]
0.591689393 seconds time elapsed