TExcelTAD

Mini Project: Speed Up a Slow C++ Build

Time to apply the course to one code base. SlowGame is a small but deliberately badly structured C++ project: sixteen subsystem files, and every one of them includes a common.hpp that drags in <algorithm>, <map>, <regex>, <string> and <vector>. It's what many real projects look like after a few years.

Over two lessons you will:

  1. Measure the baseline with deterministic numbers (this lesson).
  2. Add a precompiled header and prove what it saves (this lesson).
  3. Turn on a unity build, hit one of its pitfalls and fix it (part 2).
  4. Add ccache and prove that clean rebuilds become cache hits (part 2).
  5. Summarise everything in a scorecard (part 2).

Every session recreates the project from scratch with the same generator script, so each one stands alone. No session prints a time: the evidence is compile counts, header opens, preprocessed lines and cache statistics, which come out the same on every machine.

The project

bash
mkdir -p slowgame/src && cd slowgame
cat > src/common.hpp <<'H'
#pragma once
#include <algorithm>
#include <map>
#include <regex>
#include <string>
#include <vector>
H
systems="audio input physics render net ui save script anim ai fx world camera loader config log"
for s in $systems; do cat > src/$s.cpp <<SRC
#include "common.hpp"
namespace { int weight(const std::string& name) { return int(name.size()); } }
int ${s}_update() {
  std::map<std::string, std::vector<int>> data{{"$s", {3, 1, 2}}};
  std::sort(data["$s"].begin(), data["$s"].end());
  return weight("$s") + (std::regex_match("$s", std::regex("[a-z]+")) ? 1 : 0);
}
SRC
done
{ for s in $systems; do echo "int ${s}_update();"; done
  echo 'int main() { int total = 0;'
  for s in $systems; do echo "  total += ${s}_update();"; done
  echo '  return total > 0 ? 0 : 1; }'; } > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(SlowGame CXX)
option(USE_PCH "precompile the heavy standard headers" OFF)
file(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)
add_executable(slowgame ${SRCS})
set_target_properties(slowgame PROPERTIES UNITY_BUILD_UNIQUE_ID UNITY_ID)
if(USE_PCH)
  target_precompile_headers(slowgame PRIVATE <algorithm> <map> <regex> <string> <vector>)
endif()
CM

Seventeen source files (sixteen subsystems + main.cpp), one target. The USE_PCH option and the UNITY_BUILD_UNIQUE_ID property are already in place for the later steps; they do nothing yet.

Step 0: the baseline

Four numbers describe the starting point: how many commands a clean build runs, how many headers the compiler opens in total (-H), how big one subsystem TU is after preprocessing, and how many files recompile when someone edits common.hpp. Plus the no-op check:

bash · try it yourself
mkdir -p slowgame/src && cd slowgame
cat > src/common.hpp <<'H'
#pragma once
#include <algorithm>
#include <map>
#include <regex>
#include <string>
#include <vector>
H
systems="audio input physics render net ui save script anim ai fx world camera loader config log"
for s in $systems; do cat > src/$s.cpp <<SRC
#include "common.hpp"
namespace { int weight(const std::string& name) { return int(name.size()); } }
int ${s}_update() {
  std::map<std::string, std::vector<int>> data{{"$s", {3, 1, 2}}};
  std::sort(data["$s"].begin(), data["$s"].end());
  return weight("$s") + (std::regex_match("$s", std::regex("[a-z]+")) ? 1 : 0);
}
SRC
done
{ for s in $systems; do echo "int ${s}_update();"; done
  echo 'int main() { int total = 0;'
  for s in $systems; do echo "  total += ${s}_update();"; done
  echo '  return total > 0 ? 0 : 1; }'; } > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(SlowGame CXX)
option(USE_PCH "precompile the heavy standard headers" OFF)
file(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)
add_executable(slowgame ${SRCS})
set_target_properties(slowgame PROPERTIES UNITY_BUILD_UNIQUE_ID UNITY_ID)
if(USE_PCH)
  target_precompile_headers(slowgame PRIVATE <algorithm> <map> <regex> <string> <vector>)
endif()
CM
cmake -S . -B base -G Ninja -DCMAKE_CXX_FLAGS=-H > /dev/null
cmake --build base > base.log 2>&1 && ./base/slowgame && echo "slowgame runs"
echo "clean build:        $(grep -c '^\[' base.log) commands, $(grep -c 'Building CXX' base.log) compiles"
echo "header opens:       $(grep -c '^\.' base.log)"
per_tu=$(g++ -std=gnu++17 -E -I src src/audio.cpp | wc -l)
echo "audio.cpp after -E: $per_tu lines"
echo "16 subsystem TUs:   $((per_tu * 16)) preprocessed lines"
echo "no-op build:        $(cmake --build base 2>&1 | tail -1)"
sleep 1 && touch src/common.hpp
echo "edit common.hpp:    $(cmake --build base 2>&1 | grep -c 'Building CXX') recompiles"
slowgame runs
clean build:        19 commands, 17 compiles
header opens:       4256
audio.cpp after -E: 72388 lines
16 subsystem TUs:   1158208 preprocessed lines
no-op build:        ninja: no work to do.
edit common.hpp:    16 recompiles

Read the baseline like a build engineer:

  • 19 commands: one compile per source file (17), the link, and CMake's re-check of the file(GLOB CONFIGURE_DEPENDS) directories. The whole cost scales with the number of TUs.
  • Each subsystem file is seven lines of code but over 72 000 lines after preprocessing, more than a million for the sixteen of them; almost all of it is the same standard-library text, parsed again in every TU.
  • The no-op build is clean (no work to do): no hygiene bug to fix first.
  • common.hpp is a full-rebuild trigger: one edit, every subsystem recompiles. Keep that in mind for step 1.

Step 1: a precompiled header

The heavy headers are standard-library headers that never change, which is the ideal PCH content. The project already has the option; turn it on and measure the same things:

bash · try it yourself
mkdir -p slowgame/src && cd slowgame
cat > src/common.hpp <<'H'
#pragma once
#include <algorithm>
#include <map>
#include <regex>
#include <string>
#include <vector>
H
systems="audio input physics render net ui save script anim ai fx world camera loader config log"
for s in $systems; do cat > src/$s.cpp <<SRC
#include "common.hpp"
namespace { int weight(const std::string& name) { return int(name.size()); } }
int ${s}_update() {
  std::map<std::string, std::vector<int>> data{{"$s", {3, 1, 2}}};
  std::sort(data["$s"].begin(), data["$s"].end());
  return weight("$s") + (std::regex_match("$s", std::regex("[a-z]+")) ? 1 : 0);
}
SRC
done
{ for s in $systems; do echo "int ${s}_update();"; done
  echo 'int main() { int total = 0;'
  for s in $systems; do echo "  total += ${s}_update();"; done
  echo '  return total > 0 ? 0 : 1; }'; } > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(SlowGame CXX)
option(USE_PCH "precompile the heavy standard headers" OFF)
file(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)
add_executable(slowgame ${SRCS})
set_target_properties(slowgame PROPERTIES UNITY_BUILD_UNIQUE_ID UNITY_ID)
if(USE_PCH)
  target_precompile_headers(slowgame PRIVATE <algorithm> <map> <regex> <string> <vector>)
endif()
CM
for pch in OFF ON; do
  cmake -S . -B b-$pch -G Ninja -DUSE_PCH=$pch -DCMAKE_CXX_FLAGS=-H > /dev/null
  cmake --build b-$pch > b-$pch.log 2>&1
  echo "USE_PCH=$pch: $(grep -c '^\[' b-$pch.log) commands, $(grep -c '^\.' b-$pch.log) header opens, $(grep -c '^!' b-$pch.log) PCH loads"
done
./b-ON/slowgame && echo "slowgame with PCH runs"
echo "PCH contents: $(echo '#include "b-ON/CMakeFiles/slowgame.dir/cmake_pch.hxx"' | g++ -std=gnu++17 -x c++ -E - | wc -l) preprocessed lines, parsed once"
sleep 1 && touch src/common.hpp
echo "edit common.hpp with PCH: $(cmake --build b-ON 2>&1 | grep -c 'Building CXX') recompiles"
USE_PCH=OFF: 19 commands, 4256 header opens, 0 PCH loads
USE_PCH=ON: 20 commands, 96 header opens, 17 PCH loads
slowgame with PCH runs
PCH contents: 72384 preprocessed lines, parsed once
edit common.hpp with PCH: 16 recompiles
  • One extra command (building the .gch) and seventeen PCH loads: every TU, including main.cpp, now starts from the precompiled state instead of parsing the standard headers.
  • Header opens collapse from 4256 to 96 (about six per TU); the parse of the heavy headers happens once, while the PCH is built.
  • common.hpp is still a rebuild trigger for every subsystem, because each .cpp includes it. The PCH made each recompile cheaper, not fewer. Splitting common.hpp (so each file includes only what it uses) would be the next refactor in a real project.

Scorecard so far

Step Clean build commands Header opens Std headers parsed Edit common.hpp
Baseline 19 4256 16× 16 recompiles
+ PCH 20 96 once 16 (cheaper) recompiles

Part 2 adds a unity build and ccache, and completes the table: Mini Project, Part 2.

Test yourself

Why does the PCH build run one more command than the baseline?

  1. CMake adds a test
  2. The precompiled header itself is compiled once before the sources
  3. The link runs twice
  4. ccache is involved

After adding the PCH, editing common.hpp still recompiled every subsystem. Why?

  1. The PCH is broken
  2. Every .cpp includes common.hpp, so they all depend on it; the PCH only makes each compile cheaper
  3. Ninja ignores PCHs
  4. Because of -H

Why are header opens and preprocessed lines good evidence for this lesson?

  1. They are faster to read
  2. They are deterministic, so the before/after comparison is the same on every machine
  3. They equal compile time exactly
  4. CMake requires them