学习可能()和不太可能()编译器提示的样本

我如何向学生展示likelyunlikely编译器提示的可用性( __builtin_expect )?

你能编写一个示例代码吗,这些代码比较没有提示的代码会快几倍。

这是我使用的那个,斐波纳契数的一个非常低效的实现:

 #include  #include  #include  #include  #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) uint64_t fib(uint64_t n) { if (opt(n == 0 || n == 1)) { return n; } else { return fib(n - 2) + fib(n - 1); } } int main(int argc, char **argv) { int i, max = 45; clock_t tm; if (argc == 2) { max = atoi(argv[1]); assert(max > 0); } else { assert(argc == 1); } tm = -clock(); for (i = 0; i <= max; ++i) printf("fib(%d) = %" PRIu64 "\n", i, fib(i)); tm += clock(); printf("Time elapsed: %.3fs\n", (double)tm / CLOCKS_PER_SEC); return 0; } 

为了演示,使用GCC:

 ~% gcc -O2 -Dopt= -o test-nrm test.c ~% ./test-nrm ... fib(45) = 1134903170 Time elapsed: 34.290s ~% gcc -O2 -Dopt=unlikely -o test-opt test.c ~% ./test-opt ... fib(45) = 1134903170 Time elapsed: 33.530s 

减少几百毫秒。 该增益是由程序员辅助的分支预测引起的。

但是现在,对于程序员应该做的事情而言:

 ~% gcc -O2 -Dopt= -fprofile-generate -o test.prof test.c ~% ./test.prof ... fib(45) = 1134903170 Time elapsed: 77.530s /this run is slowed down by profile generation. ~% gcc -O2 -Dopt= -fprofile-use -o test.good test.c ~% ./test.good fib(45) = 1134903170 Time elapsed: 17.760s 

通过编译器辅助运行时分析,我们设法从原来的34.290s减少到17.760s。 比程序员辅助的分支预测好多了!