• Using likely/unlikely in a while loop

    From Richard Kettlewell@21:1/5 to thedeerhunter1978@movie.uni on Fri Mar 17 23:34:14 2017
    TDH1978 <thedeerhunter1978@movie.uni> writes:
    I googled this and could not find an answer. I know that the
    gcc-specific keywords "likely" and "unlikely" can be useful in 'if' conditions

    if (unlikely(i < 0))
    // action

    but can they be used in a 'while' loop?

    while (likely(i > 0))
    // action

    The GCC-specific keyword is __builtin_expect, documented in https://gcc.gnu.org/onlinedocs/gcc-6.3.0/gcc/Other-Builtins.html

    ‘likely’ and ‘unlikely’ are macros defined using this keyword in some projects (e.g. the Linux kernel).

    --
    http://www.greenend.org.uk/rjk/

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From TDH1978@21:1/5 to All on Fri Mar 17 19:26:16 2017
    I googled this and could not find an answer. I know that the
    gcc-specific keywords "likely" and "unlikely" can be useful in 'if'
    conditions

    if (unlikely(i < 0))
    // action

    but can they be used in a 'while' loop?

    while (likely(i > 0))
    // action

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Jorgen Grahn@21:1/5 to All on Sun Mar 19 06:53:58 2017
    On Fri, 2017-03-17, TDH1978 wrote:
    I googled this and could not find an answer. I know that the
    gcc-specific keywords "likely" and "unlikely" can be useful in 'if'

    Like someone else explained, they actual keyword is different.

    conditions

    if (unlikely(i < 0))
    // action

    but can they be used in a 'while' loop?

    while (likely(i > 0))
    // action

    I expect so. Why not? while(unlikely(...)) seems more useful than while(likely(...)) since I expect the compiler to optimize for the
    latter case by default.

    And there are around 150 examples in the Linux kernel (or was in
    3.16.7, which I happened to have handy).

    It's probably not something you should sprinkle your code with though.

    /Jorgen

    --
    // Jorgen Grahn <grahn@ Oo o. . .
    \X/ snipabacken.se> O o .

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)