TExcelTAD

Build Performance Exercises

Each exercise is a small calculation that build engineers do all the time, written as a pure function with its tests already in place. Run the starter first: it prints wrong answers (zeros, None), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution.

Exercise 1: Hit rate from ccache statistics

Topics: How ccache Works

ccache --print-stats prints name<TAB>value lines. Return the hit rate in percent, rounded to one decimal: (direct hits + preprocessed hits) / (hits + misses). Return 0.0 when there were no cacheable calls.

python · try it yourself
def hit_rate(stats_text):
    # TODO: parse the lines into a dict and compute the rate
    return 0.0

ci_job = "cache_miss\t12\ncalled_for_link\t3\ndirect_cache_hit\t80\npreprocessed_cache_hit\t8\n"
print(hit_rate(ci_job))
print(hit_rate("cache_miss\t5\ndirect_cache_hit\t0\npreprocessed_cache_hit\t0\n"))
print(hit_rate("called_for_link\t2\n"))
0.0
0.0
0.0

Expected output:

text
88.0
0.0
0.0
Show solution
python
def hit_rate(stats_text):
    stats = {}
    for line in stats_text.strip().splitlines():
        name, value = line.split("\t")
        stats[name] = int(value)
    hits = stats.get("direct_cache_hit", 0) + stats.get("preprocessed_cache_hit", 0)
    total = hits + stats.get("cache_miss", 0)
    return round(100 * hits / total, 1) if total else 0.0

Links (called_for_link) are not cacheable calls, so they don't count.

Exercise 2: Unity batches

Topics: Unity Builds

CMake's BATCH mode puts at most batch_size sources into each unity file. Return the list of batch sizes for n sources (all full batches first, then the remainder).

python · try it yourself
def unity_batches(n, batch_size=8):
    # TODO
    return []

print(unity_batches(13))
print(unity_batches(16))
print(unity_batches(5, 2))
print(unity_batches(0))
[]
[]
[]
[]

Expected output:

text
[8, 5]
[8, 8]
[2, 2, 1]
[]
Show solution
python
def unity_batches(n, batch_size=8):
    full, rest = divmod(n, batch_size)
    return [batch_size] * full + ([rest] if rest else [])

Exercise 3: Critical path

Topics: Model: The Critical Path

Given step durations and each step's inputs, return the length of the longest dependency chain ending at target.

python · try it yourself
def critical_path(dur, deps, target):
    # TODO: earliest finish = own duration + latest finish among inputs
    return 0

dur = {"gen": 5, "a.o": 2, "b.o": 4, "lib": 1, "main.o": 3, "app": 2}
deps = {"b.o": ["gen"], "lib": ["a.o", "b.o"], "app": ["lib", "main.o"]}
print(critical_path(dur, deps, "app"))
print(critical_path(dur, deps, "lib"))
print(critical_path(dur, deps, "a.o"))
0
0
0

Expected output:

text
12
10
2
Show solution
python
def critical_path(dur, deps, target):
    memo = {}
    def finish(x):
        if x not in memo:
            memo[x] = dur[x] + max((finish(d) for d in deps.get(x, [])), default=0)
        return memo[x]
    return finish(target)

Exercise 4: Amdahl's law

Topics: Model: Parallel Builds & Amdahl's Law

Return the speed-up for serial fraction s and p workers, rounded to two decimals, and the smallest number of workers that reaches at least goal× (or None if the goal is above the limit 1/s).

python · try it yourself
def speedup(s, p):
    # TODO
    return 0.0

def workers_for(s, goal):
    # TODO: try p = 1, 2, 3, ... while the goal is reachable
    return None

print(speedup(0.1, 8), speedup(0.05, 64))
print(workers_for(0.1, 5), workers_for(0.02, 25), workers_for(0.1, 12))
0.0 0.0
None None None

Expected output:

text
4.71 15.42
9 49 None
Show solution
python
def speedup(s, p):
    return round(1 / (s + (1 - s) / p), 2)

def workers_for(s, goal):
    if goal >= 1 / s:
        return None
    p = 1
    while 1 / (s + (1 - s) / p) < goal:
        p += 1
    return p

Exercise 5: Header cost ranking

Topics: Header Cost & Build Analyzers

Given each TU's list of included headers and each header's preprocessed line count, return the headers sorted by total cost (lines × number of including TUs), highest first, as (header, cost) pairs. Break ties by name.

python · try it yourself
def rank_headers(includes, lines):
    # TODO
    return []

includes = {
    "main.cpp": ["common.hpp", "app.hpp"],
    "net.cpp": ["common.hpp", "net.hpp"],
    "ui.cpp": ["common.hpp", "app.hpp"],
    "json.cpp": ["json.hpp"],
}
lines = {"common.hpp": 30000, "app.hpp": 200, "net.hpp": 45000, "json.hpp": 90000}
for header, cost in rank_headers(includes, lines):
    print(header, cost)

Expected output:

text
common.hpp 90000
json.hpp 90000
net.hpp 45000
app.hpp 400
Show solution
python
from collections import Counter

def rank_headers(includes, lines):
    count = Counter(h for hs in includes.values() for h in hs)
    costs = [(h, n * lines[h]) for h, n in count.items()]
    return sorted(costs, key=lambda hc: (-hc[1], hc[0]))

Exercise 6: Retention: keep the last N per branch

Topics: Retention & Cleanup Policies

Builds are (branch, number, released) tuples. Return the sorted build numbers to delete: everything that is neither released nor among the keep highest numbers of its branch.

python · try it yourself
def to_delete(builds, keep=2):
    # TODO
    return []

builds = [("main", 10, False), ("main", 11, True), ("main", 12, False), ("main", 13, False),
          ("dev", 20, False), ("dev", 21, False), ("dev", 22, False), ("old", 5, False)]
print(to_delete(builds))
print(to_delete(builds, keep=1))
print(to_delete(builds, keep=5))
[]
[]
[]

Expected output:

text
[10, 20]
[10, 12, 20, 21]
[]
Show solution
python
def to_delete(builds, keep=2):
    newest = {}
    for branch, number, _ in sorted(builds, key=lambda b: -b[1]):
        newest.setdefault(branch, [])
        if len(newest[branch]) < keep:
            newest[branch].append(number)
    return sorted(n for branch, n, released in builds
                  if not released and n not in newest[branch])

Build 11 of main is old but released, so it stays whatever keep is.

Test yourself

Why don't called_for_link calls count toward ccache's hit rate?

  1. They are always hits
  2. Links aren't cacheable calls
  3. They are counted twice
  4. ccache doesn't see them

With s = 0.1, why can no number of workers reach a 12x speed-up?

  1. Too few jobs
  2. The limit is 1/s = 10x
  3. Ninja caps it
  4. Because of the link