我在 C 中有一个这样的函数(在伪代码中,删除不重要的部分):
int func(int s, int x, int *a, int *r) {
int i;
// do some stuff
for (i = 0; i < a_really_big_int; ++i) {
if (s)
r[i] = x ^ i;
else
r[i] = x ^ a[i];
// and maybe a couple other ways of computing r
// that are equally fast individually
}
// do some other stuff
}
Run Code Online (Sandbox Code Playgroud)
这段代码被调用得太多,以至于这个循环实际上是代码中的速度瓶颈。我想知道几件事:
由于 switchs是函数中的常量,好的编译器会优化循环,以便分支不会一直减慢速度吗?
如果没有,优化这段代码的好方法是什么?
====
编辑:这是一个包含更完整示例的更新:
int func(int s,
int start, int stop, …Run Code Online (Sandbox Code Playgroud) c optimization loops micro-optimization compiler-optimization