2008年6月3日 星期二

likely & unlikely part II

剛剛在 Understanding Linux Network Internals 上看到的, 節錄出來一下以免以後忘了... :p


1.2.9. Compile-Time Optimization for Condition Checks

Most of the time, when the kernel compares a variable against some external value to see whether a given condition is met, the result is extremely likely to be predictable. This is pretty common, for example, with code that enforces sanity checks. The kernel uses the likely and unlikely macros, respectively, to wrap comparisons that are likely to return a true (1) or false (0) result. Those macros take advantage of a feature of the gcc compiler that can optimize the compilation of the code based on that information.

Here is an example. Let's suppose you need to call the do_something function, and that in case of failure, you must handle it with the handle_error function:

err = do_something(x,y,z);
if (err)
handle_error(err);

Under the assumption that do_something rarely fails, you can rewrite the code as follows:

err = do_something(x,y,z);
if (unlikely(err))
handle_error(err);

An example of the optimization made possible by the likely and unlikely macros is in handling options in the IP header. The use of IP options is limited to very specific cases, and the kernel can safely assume that most IP packets do not carry IP options. When the kernel forwards an IP packet, it needs to take care of options according to the rules described in Chapter 18. The last stage of forwarding an IP packet is taken care of by ip_forward_finish. This function uses the unlikely macro to wrap the condition that checks whether there is any IP option to take care of. See the section "ip_forward_finish Function" in Chapter 20.


基本上跟先前的認知是一樣的, 但發覺 ARM, MIPS 跟 PowerPC 用的 GNU crosscompiler 似乎都不會去做這些個 optimization... x86 的就會...

沒有留言: