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

osg*_*sgx 11 c optimization gcc likely-unlikely

我如何能证明对学生的可用性likelyunlikely编译器提示(__builtin_expect)?

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

Jul*_*ano 23

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

#include <stdio.h>
#include <inttypes.h>
#include <time.h>
#include <assert.h>

#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;
}
Run Code Online (Sandbox Code Playgroud)

为了演示,使用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
Run Code Online (Sandbox Code Playgroud)

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

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

~% 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
Run Code Online (Sandbox Code Playgroud)

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

  • aah,tm = -clock(); tm + = clock(); 很漂亮,我以前没看过,谢谢! (19认同)
  • 上面代码中实际使用的"可能"和"不太可能"在哪里? (8认同)