Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Using likely/unlikely in a while loop

315 views
Skip to first unread message

TDH1978

unread,
Mar 17, 2017, 7:26:18 PM3/17/17
to
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

Richard Kettlewell

unread,
Mar 17, 2017, 7:34:15 PM3/17/17
to
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/

Jorgen Grahn

unread,
Mar 19, 2017, 2:54:02 AM3/19/17
to
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 .
0 new messages