PDA

View Full Version : Questions to Q_LIKELY / Q_UNLIKELY



HappyCoder
17th March 2016, 10:23
Hello,

i have some questions to Q_LIKELY and Q_UNLIKEYLY.
In Qt Docs they wrote it will help the compiler to optimize the code.

Questions:
1.) Does that really give an advantage in speed of my code? I found here in forum
that also the CPU must support it and the benefit of it is not so much.

2.) What if i have two expr. to evaluate



if( expr1 || expr2 )

// Which one is prefered
if( Q_LIKELY(exp1) || Q_LIKELY(expr2) ) // two Q_LIKELY
or
if( Q_LIKELY(exp1 || expr2) ) // in one Q_LIKELY


Thx

wysota
17th March 2016, 10:52
Hello,

i have some questions to Q_LIKELY and Q_UNLIKEYLY.
In Qt Docs they wrote it will help the compiler to optimize the code.

Questions:
1.) Does that really give an advantage in speed of my code? I found here in forum
that also the CPU must support it and the benefit of it is not so much.

It depends on the CPU architecture and how often such test is executed.


2.) What if i have two expr. to evaluate



if( expr1 || expr2 )

// Which one is prefered
if( Q_LIKELY(exp1) || Q_LIKELY(expr2) ) // two Q_LIKELY
or
if( Q_LIKELY(exp1 || expr2) ) // in one Q_LIKELY



Basically you should (if semantically possible) put the more probable test first and wrap it in a likely statement (assuming it is likely the test succeeds). That will make the compiler prepare a branch instruction before executing the first test. Since the branch is likely, it makes little sense to set the second expression as likely. Unless of course you want to say that at least one of the tests is likely to pass (without determining which one), then the latter statement is better (however you will probably gain less by using it). So all in all, these are two different cases which can't be substituted by one another.