Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to speed up g++ compile time (when using a lot of templates)

This question is perhaps somehow odd, but how can I speed up g++ compile time? My C++ code heavily uses boost and templates. I already moved as much as possible out of the headers files and use the -j option, but still it takes quite a while to compile (and link).

Are there any tools out there which analyse my code and point out bottle-necks for the compiler? Or can one somehow profile the compiler running on my code? This would be really nice, because sometimes I have the impression, that I spent too much time staring at the compiler console log ...

like image 554
Danvil Avatar asked Aug 03 '10 13:08

Danvil


People also ask

Why are templates compiling slowly?

C++ in general is slow to compile because of the ancient include mechanism, which causes the compiler to recursively re-parse every header with all its declarations and definitions and all that's included for every translation unit. Templates just build on that "feature".

Are templates faster C++?

The reason templates are considered faster is that they are visible to the compiler.

Are templates compile-time or runtime?

All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!


2 Answers

What has been most useful for me:

  • Build on a RAM filesystem. This is trivial on Linux. You may want to keep a copy of common header files (precompiled or the actual .h files) on the RAM filesystem as well.
  • Precompiled headers. I have one per (major) library (e.g. Boost, Qt, stdlib).
  • Declare instead of include classes where possible. This reduces dependencies, thus reduces the number of files which need to be recompiled when you change a header file.
  • Parallelize make. This usually helps on a case-by-case basis, but I have -j3 globally for make. Make sure your dependency graphs are correct in your Makefile, though, or you may have problems.
  • Use -O0 if you're not testing execution speed or code size (and your computer is fast enough for you not to care much about the (probably small) performance hit).
  • Compile each time you save. Some people don't like this, but it allows you to see errors early and can be done in the background, reducing the time you have to wait when you're done writing and ready to test.
like image 197
strager Avatar answered Sep 20 '22 21:09

strager


Here's what I've done to speed up builds under a very similar scenario that you describe (boost, templates, gcc)

  • build on local disk instead of a network file system like NFS
  • upgrade to a newer version of gcc
  • investigate distcc
  • faster build systems, especially more RAM
like image 23
Sam Miller Avatar answered Sep 18 '22 21:09

Sam Miller