TExcelTAD
Home › Build Performance & Artifacts: ccache, sccache, Distributed Builds, Artifact Repositories › Mini Project, Part 2: Unity Build, ccache & the Scorecard

Mini Project, Part 2: Unity Build, ccache & the Scorecard

Part 1 measured SlowGame and added a precompiled header. This part reduces the number of compiles with a unity build, makes clean rebuilds nearly free with ccache, and ends with a scorecard of every configuration, all measured in one deterministic session.

Each session starts by recreating the project with the same generator as in part 1:

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

Step 2: a unity build, and its first pitfall

Seventeen files at the default batch size of 8 should become three unity TUs. Try it:

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 unity -G Ninja -DCMAKE_UNITY_BUILD=ON > /dev/null
cmake --build unity 2>&1 | grep -m2 -E 'error|note' | sed 's#/home/learner/slowgame/##'
src/net.cpp:2:17: error: redefinition of ‘int {anonymous}::weight(const std::string&)’
src/log.cpp:2:17: note: ‘int {anonymous}::weight(const std::string&)’ previously defined here

Every subsystem has its own namespace { int weight(…) }, which is fine in separate TUs and a redefinition in a unity TU (Unity Build Pitfalls). The CMake target already sets UNITY_BUILD_UNIQUE_ID UNITY_ID, so the fix is the documented pattern: wrap the helper in namespace UNITY_ID, call it as UNITY_ID::weight, and define UNITY_ID as empty for normal builds:

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 f in src/*.cpp; do
  [ "$f" = src/main.cpp ] && continue
  sed -i -e '1a #ifndef UNITY_ID\n#define UNITY_ID\n#endif' \
         -e 's/namespace { int weight/namespace { namespace UNITY_ID { int weight/' \
         -e 's/size()); } }/size()); } } }/' \
         -e 's/return weight(/return UNITY_ID::weight(/' "$f"
done
sed -n '1,6p' src/audio.cpp
for unity in OFF ON; do
  cmake -S . -B u-$unity -G Ninja -DCMAKE_UNITY_BUILD=$unity -DCMAKE_CXX_FLAGS=-H > /dev/null
  cmake --build u-$unity > u-$unity.log 2>&1 && ./u-$unity/slowgame
  echo "UNITY=$unity: $(grep -c 'Building CXX' u-$unity.log) compiles, $(grep -c '^\.' u-$unity.log) header opens"
done
ls u-ON/CMakeFiles/slowgame.dir/Unity/ | grep -c 'cxx
  


sleep 1 && touch src/audio.cpp
echo "edit audio.cpp, unity build: recompiles $(cmake --build u-ON 2>&1 | grep -c 'Building CXX') unity TU"
#include "common.hpp"
#ifndef UNITY_ID
#define UNITY_ID
#endif
namespace { namespace UNITY_ID { int weight(const std::string& name) { return int(name.size()); } } }
int audio_update() {
UNITY=OFF: 17 compiles, 4256 header opens
UNITY=ON: 3 compiles, 815 header opens
3
edit audio.cpp, unity build: recompiles 1 unity TU
  • The code now compiles both ways, which is the point of the #ifndef guard: CI keeps one job without unity to catch missing includes.
  • Seventeen compiles became three, and the standard headers are parsed three times instead of sixteen: 815 header opens instead of 4256 (the count also includes the .cpp files that the unity sources include).
  • Editing one file recompiles its whole batch: a single compile, but of eight files' worth of code. That's the incremental cost of unity builds.

Step 3: ccache

Now the cache. The scenario: a developer builds, deletes the build directory (or switches branches back and forth), and builds again; then a second checkout of the same commit is built elsewhere on the machine:

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 f in src/*.cpp; do
  [ "$f" = src/main.cpp ] && continue
  sed -i -e '1a #ifndef UNITY_ID\n#define UNITY_ID\n#endif' \
         -e 's/namespace { int weight/namespace { namespace UNITY_ID { int weight/' \
         -e 's/size()); } }/size()); } } }/' \
         -e 's/return weight(/return UNITY_ID::weight(/' "$f"
done
cp -r /home/learner/slowgame /home/learner/slowgame-review
st() { ccache --print-stats | awk -F'\t' '$1 ~ /^(direct_cache_hit|preprocessed_cache_hit|cache_miss)$/ { printf "%s=%s ", $1, $2 } END { print "" }' | sed 's/ $//'; }
export CCACHE_BASEDIR=/home/learner
b() { rm -rf $1/build; cmake -S $1 -B $1/build -G Ninja -DCMAKE_CXX_COMPILER_LAUNCHER=ccache > /dev/null
      ccache -z > /dev/null; cmake --build $1/build > /dev/null; echo "$2: $(st)"; }
b /home/learner/slowgame "first clean build      "
b /home/learner/slowgame "clean rebuild          "
b /home/learner/slowgame-review "second checkout        "
first clean build      : cache_miss=17 direct_cache_hit=0 preprocessed_cache_hit=0
clean rebuild          : cache_miss=0 direct_cache_hit=17 preprocessed_cache_hit=0
second checkout        : cache_miss=0 direct_cache_hit=17 preprocessed_cache_hit=0

The first build fills the cache (17 misses). After that, a clean rebuild and a build in a different checkout are all direct hits: the compiler doesn't run at all, only the link does. base_dir is what makes the second checkout hit (lesson).

The scorecard

The last session builds every configuration from clean and collects all the deterministic measures in one table. For configurations with ccache, it builds twice (the first build warms the cache) and reports the second one, with pch_defines,time_macros sloppiness so ccache can cache PCH compiles (lesson):

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 f in src/*.cpp; do
  [ "$f" = src/main.cpp ] && continue
  sed -i -e '1a #ifndef UNITY_ID\n#define UNITY_ID\n#endif' \
         -e 's/namespace { int weight/namespace { namespace UNITY_ID { int weight/' \
         -e 's/size()); } }/size()); } } }/' \
         -e 's/return weight(/return UNITY_ID::weight(/' "$f"
done
export CCACHE_SLOPPINESS=pch_defines,time_macros,include_file_mtime,include_file_ctime
row() {   # name, cmake options, use ccache?
  rm -rf b && cmake -S . -B b -G Ninja -DCMAKE_CXX_FLAGS=-H $2 > /dev/null
  if [ "$3" = yes ]; then cmake --build b > /dev/null 2>&1; rm -rf b; cmake -S . -B b -G Ninja -DCMAKE_CXX_FLAGS=-H $2 > /dev/null; ccache -z > /dev/null; fi
  cmake --build b > log 2>&1 && ./b/slowgame || echo "BUILD FAILED"
  compiles=$(grep -c 'Building CXX' log); opens=$(grep -c '^\.' log)
  hits=$(ccache --print-stats | awk -F'\t' '$1 == "direct_cache_hit" { print $2 }')
  [ "$3" = yes ] || hits=-
  printf '| %-22s | %8s | %12s | %10s |\n' "$1" "$compiles" "$opens" "$hits"
}
printf '| %-22s | %8s | %12s | %10s |\n' configuration compiles "header opens" "cache hits"
echo "|------------------------|----------|--------------|------------|"
row "baseline"            ""                                        no
row "PCH"                 "-DUSE_PCH=ON"                            no
row "unity"               "-DCMAKE_UNITY_BUILD=ON"                  no
row "unity + PCH"         "-DCMAKE_UNITY_BUILD=ON -DUSE_PCH=ON"     no
row "unity + PCH + ccache" "-DCMAKE_UNITY_BUILD=ON -DUSE_PCH=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" yes
| configuration          | compiles | header opens | cache hits |
|------------------------|----------|--------------|------------|
| baseline               |       17 |         4256 |          - |
| PCH                    |       18 |           96 |          - |
| unity                  |        3 |          815 |          - |
| unity + PCH            |        4 |           35 |          - |
| unity + PCH + ccache   |        4 |           35 |          4 |

How to read it:

  • compiles is the number of compiler invocations Ninja scheduled. PCH adds one; unity divides by the batch size.
  • header opens is the work the preprocessor did; it drops with each step, from 4256 to 35. In the ccache row it still reads 35, but nothing was opened: ccache stores the compiler's stderr with each result and replays it on a hit, so the -H lines are a recording of the original compile.
  • cache hits with the warm cache equal the number of compiles (4 of 4): the clean rebuild ran the compiler zero times, only the link.

From this table you can estimate the time each step saves with the models and your own per-TU compile times, but you no longer need a stopwatch to know that each step works.

What you'd do next in a real project

  • Split common.hpp so each subsystem includes only what it uses; that fixes the "edit one header, rebuild everything" problem that PCH and unity builds don't touch.
  • Move the <regex> user behind a function so fewer TUs need it (Forward Declarations).
  • In CI: ccache with base_dir, compiler_check = content and a saved cache directory; one job without unity and PCH.
  • Publish the built library to an artifact repository if other projects consume it, instead of letting each of them rebuild it (CI Caches vs Artifact Repositories).

Test yourself

Why did the unity build fail before the fix?

  1. Too many files
  2. Each subsystem's anonymous-namespace weight() collided in the same unity TU
  3. The PCH was missing
  4. ccache was on

In the ccache row, the -H header-open count is the same as without ccache although the compiler never ran. Why?

  1. -H disables caching
  2. ccache stores each compile's stderr and replays it on a hit
  3. The PCH was rebuilt
  4. Unity builds bypass ccache

Which problem do PCH, unity builds and ccache NOT solve here?

  1. Repeated header parsing
  2. Clean rebuild cost
  3. Editing common.hpp still invalidates every subsystem TU
  4. Number of compiles