Thursday, March 11, 2010

Are you smarter than a compiler?

I recently read a survey about C compilers by Felix von Leitner published in Linux Kongress 2009, and was surprised by how smart modern C compilers are.
For example, to calculate the absolute value of a 64-bit signed integer, you need:
    x > 0 ? x : -x
The compiler optimizes into branchless code:
    long tmp = x >> 63;
    return (tmp ^ x) - tmp;
Since a mispredicted branch cost 10 cycles, and CPU could issue 4 instructions per cycle, such a branchless variation is a lot faster but much less readable by human.
I still remember the days where I use "++i" instead of "i++", and use "x>>2" instead of "x / 4".  But such kind of "optimizations" do not matter any more because of advancements in compiler technologies.
In most cases, it is better for us to spend time making the code more readable than getting the last bit of performance from the hardware.
Remember, readable code may be as fast as "optimized" code, and more importantly, readable code is more likely to be correct!

No comments:

Post a Comment