리눅스 & 안드로이드2013. 6. 22. 18:33

오늘 소스를 보다가 __builtin_expect 라는 함수를 보게 되었다.

소스상에서는 아무리 찾아봐도 없는 symbol.

그래서 구글링 해 보니, 아래와 같은 설명이 있었다.


— Built-in Function: long __builtin_expect (long exp, long c)


You may use __builtin_expect to provide the compiler with branch prediction information. In general, you should prefer to use actual profile feedback for this (-fprofile-arcs), as programmers are notoriously bad at predicting how their programs actually perform. However, there are applications in which this data is hard to collect.

The return value is the value of exp, which should be an integral expression. The semantics of the built-in are that it is expected that exp == c. For example:

          if (__builtin_expect (x, 0))
            foo ();

indicates that we do not expect to call foo, since we expect x to be zero. Since you are limited to integral expressions for exp, you should use constructions such as

          if (__builtin_expect (ptr != NULL, 1))
            foo (*ptr);

when testing pointer or floating-point values.


즉, __builtin_expect라는 함수는 gcc에 내장되어 있는 함수이고, x를 반환하는 단순한 기능을 한다.

그러나, runtime에 CPU가 branch prediction을 하는데 힌트를 줘서 성능을 높이는데 사용될 수 있다.

CPU가 해당 conditional branch를 수행할 때, 대부분의 경우는, 두 번째 인자인 c의 값으로 판정된다는 힌트를 줘서 branch prediction의 hit ratio를 높일 수 있다는 것.


다시 풀어 얘기하자면,

if (__builtin_expect (x, 0)) STATEMENT_A; else STATEMENT_B; 와 같은 문장을 실행하는 경우,

x는 대부분의 경우 0이라는 힌트를 줘서, CPU가 STATEMENT_B를 미리 실행할 수 있도록 해준다.


정말 모르는게 많아-_-;


P.S. 이런 친절한 설명이 있구나.

http://minjang.egloos.com/561972

http://chammoru.egloos.com/4375371 assembly로 까지 확인되어 있음 :-)

Posted by 세월의돌