C++20: difference between [[likely]], [[unlikely]] and __builtin_expect?
Asked Answered
C

1

11

Preliminary information: according to the recent ISO C++ Committee Trip Report, the [[ likely ]] and [[ unlikely ]] attributes for conditional branching will be added in C++20 and is available in the newest version of GNU GCC (you can play with it on the online compiler wandbox.org).


Question: Is the following construction

if (cond) [[ likely ]] { ... }

equivalent to the following one?

if (__builtin_expect(bool(cond), 1)) { ... }

Are there any performance difference or implementation nuances between different compilers that one should be aware of in order to use it effectively?

Chapin answered 18/7, 2019 at 12:22 Comment(0)
H
11

Is the following construction equivalent to the following one?

In intention, yes.


Are there any performance difference or implementation nuances accross compilers that one should be aware of in order to use it effectively?

As you can see from P0479, there is no mandatory wording requirement on the behavior of these attributes. Their behavior is mentioned as part of a non-normative note, which implementations are encouraged but not forced to follow.

The only way to answer this question is to check the manual of your compiler.

Haply answered 18/7, 2019 at 12:25 Comment(1)
I'd add that the __builtin* is a compiler intrinsic while [[ likely ]] is going to be a language standard, if this is not too obvious already.Melancholia

© 2022 - 2024 — McMap. All rights reserved.