r/cmake • • 19h ago

I made a tool that tells you why a clean CMake build is slow, without touching the project's settings

6 Upvotes

https://github.com/jhtrace/buildwhy

Where I work the build settings (generator, presets, flags) are owned by other people, and the clean build is slow. Most advice for that starts with changing the build: switch to Ninja, add a PCH, turn on unity builds. I wanted to know what to fix first without touching any of it, so I wrote this.

buildwhy measure --preset dev --includes --duplicates --html

That resolves the preset's build directory from CMakePresets.json / CMakeUserPresets.json (inherits and includes too), configures a copy next to it (build/dev -> build/dev-buildwhy) with the same preset, builds it from scratch, and prints a report. Your source tree, presets and usual build directory aren't touched.

Some things I had to get right for it to work on real projects:

  • Unix Makefiles: make doesn't log step times, so for the measured build buildwhy passes itself as CMAKE_<LANG>_COMPILER_LAUNCHER and _LINKER_LAUNCHER and writes its own log. The critical path follows how make actually schedules: a target starts only after everything it depends on is fully built (Ninja only makes the link wait).
  • Existing launchers: if the project already sets a launcher, for example a script that runs the compiler in a Docker container, it still runs after buildwhy's. ccache is left out so every file is really compiled.
  • Failed builds: it keeps going (make -k / ninja -k 0) and reports on what did build.

What you get: wall vs CPU time, how many jobs were really busy, the critical path, the #include lines that cost the most (with how much sooner the build would end without each), template code the linker throws away, and one offline HTML page with a 3D dependency graph and a timeline.

Example on fmt 11.1.4, with the real output: https://github.com/jhtrace/buildwhy/blob/main/docs/example-fmt.md

Linux and macOS are tested in CI, GCC and clang, MSVC isn't supported. If it gets your presets wrong, please open an issue with the preset file; that part has the most edge cases.