Return types are frequently checked for errors. But, the code that will continue to execute may be specified in different ways.
if(!ret)
{
doNoErrorCode();
}
exit(1);
or
if(ret)
{
exit(1);
}
doNoErrorCode();
One way heavyweight CPU's can speculate about the branches taken in near proximity/locality using simple statistics - I studied a 4-bit mechanism for branch speculation (-2,-1,0,+1,+2) where zero is unknown and 2 will be considered a true branch.
Considering the simple technique above, my questions are about how to structure code. I assume that there must be a convention among major compilers and major architectures. These are my two questions
- When the code isn't an often-visited loop which boolean value is biased for when the pipeline is being filled ?
- Speculation about branching must begin at either true or false or zero ( the pipeline must be filled with something). Which is it likely to be ?
The behavior varies among CPUs, and the compiler often reorders instructions. You will find all the information you need in these manuals: http://agner.org/optimize/.
In my opinion the only way to know what happens is to read the assembly code generated by the compiler.
On gcc you can use __builtin_expect
to provide the compiler with branch prediction information. To make it slightly easier you can then borrow the likely/unlikely macros used e.g. in the Linux kernel:
#define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0)
and then e.g.
if (unlikely(!some_function())
error_handling();
来源:https://stackoverflow.com/questions/1833253/preserving-the-execution-pipeline