GCC and C vs C++ Speed, Measured.
With the imminent release of gcc 4.8, GCC has finally switched to C++ as the implementation language. As usual, LWN has excellent coverage. Those with long memories will remember Linux trying to use g++ back in 1992 and retreating in horror at the larger, slower code. The main benefit was stricter typechecking, particularly for enums (a great idea: I had -Wstrict-enum patches for gcc about 12 years ago, which was a superset of the -Wenum-compare we have now, but never got it merged).
With this in mind, and Ian Taylor's bold assertion that "The C subset of C++ is as efficient as C", I wanted to test what had changed with some actual measurements. So I grabbed gcc 4.7.2 (the last release which could do this), and built it with C and C++ compilers:
- ../gcc-4.7.2/configure --prefix=/usr/local/gcc-c --disable-bootstrap --enable-languages=c,c++ --disable-multiarch --disable-multilib
- ../gcc-4.7.2/configure --prefix=/usr/local/gcc-cxx --disable-bootstrap --enable-languages=c,c++ --disable-multiarch --disable-multilib --enable-build-with-cxx
The C++-compiled binaries are slightly larger, though that's mostly debug info:
- -rwxr-xr-x 3 rusty rusty 1886551 Mar 18 17:13 /usr/local/gcc-c/bin/gcc
text data bss dec hex filename
552530 3752 6888 563170 897e2 /usr/local/gcc-c/bin/gcc - -rwxr-xr-x 3 rusty rusty 1956593 Mar 18 17:13 /usr/local/gcc-cxx/bin/gcc
text data bss dec hex filename
552731 3760 7176 563667 899d3 /usr/local/gcc-cxx/bin/gcc
Then I used them both to compile a clean Linux kernel 10 times:
- for i in `seq 10`; do time make -s CC=/usr/local/gcc-c/bin/gcc 2>/dev/null; make -s clean; done
- for i in `seq 10`; do time make -s CC=/usr/local/gcc-cxx/bin/gcc 2>/dev/null; make -s clean; done
Using stats --trim-outliers, which throws away best and worse, and we have the times for the remaining 8:
- real 14m24.359000-35.107000(25.1521+/-0.62)s
user 12m50.468000-52.576000(50.912+/-0.23)s
sys 1m24.921000-27.465000(25.795+/-0.31)s - real 14m27.148000-29.635000(27.8895+/-0.78)s
user 12m50.428000-52.852000(51.956+/-0.7)s
sys 1m26.597000-29.274000(27.863+/-0.66)s
So the C++-compiled binaries are measurably slower, though not noticably: it's about 865 seconds vs 868 seconds, or about .3%. Even if a kernel compile spends half its time linking, statting, etc, that's under 1% slowdown.
And it's perfectly explicable by the larger executable size. If we strip all the gcc binaries, and do another 10 runs of each (... flash forward to the next day.. oops, powerfail, make that 2 days later):
- real 14m24.659000-33.435000(26.1196+/-0.65)s
user 12m50.032000-57.701000(50.9755+/-0.36)s
sys 1m26.057000-28.406000(26.863+/-0.36)s - real 14m26.811000-29.284000(27.1308+/-0.17)s
user 12m51.428000-52.696000(52.156+/-0.39)s
sys 1m26.157000-27.973000(26.869+/-0.41)s
Now the difference is 0.1%, pretty much in the noise.
Summary: so whether you like C++ or not, the performance argument is moot.