TExcelTAD

Clang's -ftime-trace

.ninja_log tells you which files are slow. To learn why a file is slow, you need the compiler's own profile. Clang (9 and later) writes one with -ftime-trace: next to every object file it produces a JSON file in the Chrome trace format, with an event for every header it entered, every class it parsed, every template it instantiated and every optimisation pass it ran.

bash
clang++ -std=c++20 -O2 -ftime-trace -c widget.cpp -o widget.o   # also writes widget.json

Open the JSON in ui.perfetto.dev or chrome://tracing and you see a flame chart: Frontend (preprocessing, parsing, template instantiation) and Backend (optimisation, code generation), with nested Source events for each included header.

GCC has no equivalent trace: -ftime-report prints a table of phases with timings to stderr, which is useful but only per TU and only as text. In practice teams profile with Clang even when they ship with GCC, because the header structure is the same.

The structure of a trace

Durations change every run, but the structure of the trace doesn't, as long as every event is recorded. By default Clang drops events shorter than 500 µs (-ftime-trace-granularity), which makes the event list timing-dependent; with -ftime-trace-granularity=0 it records everything. This session compiles two TUs, one light and one that includes <regex>, and prints what's in their traces:

bash · try it yourself
mkdir -p tt && cd tt
cat > light.cpp <<'SRC'
int add(int a, int b) { return a + b; }
SRC
cat > heavy.cpp <<'SRC'
#include <regex>
#include <string>
bool is_id(const std::string& s) { return std::regex_match(s, std::regex("[a-z_][a-z0-9_]*")); }
SRC
for f in light heavy; do
  clang++ -std=c++20 -O1 -ftime-trace -ftime-trace-granularity=0 -c $f.cpp -o $f.o
done
ls *.json
cat > summarize.py <<'PY'
import collections, json, sys
for path in sys.argv[1:]:
    trace = json.load(open(path))
    events = [e for e in trace["traceEvents"] if e.get("ph") == "X"]
    names = collections.Counter(e["name"] for e in events if not e["name"].startswith("Total "))
    headers = {e["args"]["detail"] for e in events if e["name"] == "Source"}
    print(f"{path}: keys={sorted(trace)}")
    print(f"  events: {len(events)}  distinct kinds: {len(names)}  headers entered: {len(headers)}")
    for kind in ["Source", "ParseClass", "InstantiateClass", "InstantiateFunction", "CodeGen Function"]:
        print(f"  {kind:<20} {names[kind]}")
PY
python3 summarize.py light.json heavy.json
heavy.json
light.json
light.json: keys=['beginningOfTime', 'traceEvents']
  events: 466  distinct kinds: 106  headers entered: 0
  Source               0
  ParseClass           0
  InstantiateClass     0
  InstantiateFunction  0
  CodeGen Function     1
heavy.json: keys=['beginningOfTime', 'traceEvents']
  events: 260352  distinct kinds: 133  headers entered: 256
  Source               305
  ParseClass           1393
  InstantiateClass     3524
  InstantiateFunction  2627
  CodeGen Function     2208

The light TU is nearly empty: a few hundred events, mostly the backend's passes, no headers and a single function to generate. The heavy TU enters 256 different headers, parses about 1 400 classes and instantiates more than 6 000 templates (classes plus functions), then generates code for over 2 000 functions, all to define one three-line function. Every TU that includes <regex> pays that again.

The kinds of events

Event Meaning What to do when it's big
Source a header being processed (detail = path) include less, forward-declare, PCH
ParseClass, ParseFunctionDefinition parsing declarations same as above
InstantiateClass, InstantiateFunction template instantiations extern template, move heavy templates out of headers
PerformPendingInstantiations instantiations deferred to the end of the TU as above
CodeGen Function, OptFunction, RunPass backend work lower -O for debug builds, split huge functions
Total … one summary event per kind with the summed duration the quickest place to look

The Total events are the most useful part for automation: one line per category with the time summed over the TU.

Tracing a whole CMake build

Add the flag to the build, not to CMakeLists.txt, so it never ends up in a release:

bash · try it yourself
mkdir -p proj/src && cd proj
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Traced CXX)
add_executable(app src/main.cpp src/names.cpp)
CM
printf '#include <map>\n#include <string>\nint names() { std::map<std::string, int> m{{"a", 1}}; return m.size(); }\n' > src/names.cpp
printf 'int names();\nint main() { return names() - 1; }\n' > src/main.cpp
CXX=clang++ cmake -S . -B build -G Ninja -DCMAKE_CXX_FLAGS="-ftime-trace -ftime-trace-granularity=0" > /dev/null
cmake --build build > /dev/null
find build -name '*.json' -path '*app.dir*' | sort
build/CMakeFiles/app.dir/src/main.cpp.json
build/CMakeFiles/app.dir/src/names.cpp.json

Each object gets its trace next to it. Two warnings:

  • ccache won't cache compiles with -ftime-trace (it reports them as unsupported_compiler_option), so profile in a separate build directory.
  • Don't leave granularity at 0 for big builds: traces get large. The default (500 µs) is right for finding hotspots; 0 is for reproducible counting, as above.

From one trace to the whole build

One trace answers "why is this file slow". For "which headers cost the most across the whole build", you aggregate all traces. That's what ClangBuildAnalyzer (by Aras Pranckevičius) does: ClangBuildAnalyzer --all build out.bin && ClangBuildAnalyzer --analyze out.bin prints the most expensive files, headers, template instantiations and functions, summed over every TU. The next lesson builds a deterministic version of that idea from include counts.

Test yourself

Where does clang++ -ftime-trace -c a.cpp -o a.o write the trace?

  1. stderr
  2. a.json next to a.o
  3. /tmp/trace.json
  4. .ninja_log

Why does this lesson pass -ftime-trace-granularity=0?

  1. To make compiles faster
  2. So every event is recorded and event counts don't depend on timing
  3. Because GCC needs it
  4. To disable the trace

Which event kind tells you how many headers a TU entered?

  1. RunPass
  2. Source
  3. CodeGen Function
  4. InstantiateClass