Programming Search⌘K

Conceptcore

Build graph

Also called dependency graph, build dependency graph, action graph, target graph, DAG of build steps, topological order, parallel build.

A build graph links each target of a build to the inputs that it needs. A build tool runs the steps in a topological order of this graph, and runs steps in parallel when no path joins them.

Applies to
core-languages

Idea

Each step of a build needs some inputs and makes some outputs. When the output of one step is an input of another step, the second step depends on the first. These relations form a graph. The nodes are the files or the targets, and an edge goes from a target to each thing that it needs. This is the build graph, also called the dependency graph.

The build tool reads the graph from the build file. In GNU Make, the rules give it: before make can process the rule for a target, it must process the rules for the files that the target depends on.1 In Bazel, the first step of bazel build parses every BUILD file in the workspace to create a graph of dependencies among the artifacts.2 In CMake, the dependencies between the targets determine the build order and the rules for regeneration after a change.3

Three properties of the graph decide what the tool can do:

  • It has no cycles. If a target needs itself, through other targets or directly, no order can build it.
  • It gives an order. A list of the nodes in which each node comes after all the nodes that it needs is a topological order. Make runs its tasks in a topological order of the dependency graph.4
  • It shows the parallel work. Two steps with no path between them in the graph can run at the same time.

How it works

Find the part of the graph that the goal needs. The tool starts at the goal and follows the edges. Bazel uses the graph to find the transitive dependencies of the target: every target that it depends on, and every target that those targets depend on, recursively.2 Make does not process a rule that the goal does not depend on.1

Put the steps in order. A topological sort gives an order. In Kahn's method, each node keeps a count of the dependencies that are not done. The nodes with a count of zero are ready. The method takes a ready node, puts it in the order, and lowers the count of each node that needs it. A node whose count falls to zero becomes ready. Kahn published this method for large networks in 1962, for problems such as PERT charts.5 The paper calls the topological scheduler of Make one that "pre-computes a linear order of tasks".4

Run the steps in parallel. A step can start when all its dependencies are done. Bazel starts by building each target that has no other dependencies, and it starts a target as soon as all its dependencies are built.2 The paper describes the parallel form of the topological scheduler in the same way.4 If you group the steps by their depth in the graph, each group, or wave, can run at the same time when there are enough workers. The longest path in the graph is the lower limit of the time of the build, however many workers there are.

GNU Make runs one recipe at a time by default. The -j option tells it to run many recipes at the same time, and an integer after -j sets the number of job slots.6 POSIX make has the option -j maxjobs too.7 Ninja runs builds in parallel by default, with a number of jobs from the number of CPUs.8

Find a cycle. A depth-first search finds a cycle: if it reaches a node that is still on its current path, the edges from that node back to itself form a cycle. Kahn's method finds a cycle in a different way: when no node is ready, but some nodes are not in the order, those nodes are on a cycle or need a node on a cycle. The run below gives GNU Make a makefile with the cycle a.o needs gen.h, and gen.h needs a.o. GNU Make prints a message, drops one edge of the cycle, and builds the rest.

d=$(mktemp -d)
cd "$d"
cat >Makefile <<'END'
app: a.o
	@echo link app
a.o: gen.h
	@echo compile a.o
gen.h: a.o
	@echo generate gen.h
END
make 2>&1
cd /
rm -rf "${d:?}"
Output
make: Circular gen.h <- a.o dependency dropped.
generate gen.h
compile a.o
link app

A build that continues after a dropped edge can run the steps in a wrong order. Treat the message as an error in the build file.

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map of rules and a std::set or std::priority_queue of ready nodes. Alternative: The Java example.
JavaIdiom
CIdiomNodes as array indices, an adjacency list in arrays, and a queue of ready nodes in an array. Alternative: The Go example.
C#Idiom
JavaScriptIdiomA Map from each target to an array of dependencies, Kahn's method with an array of ready nodes, and a recursive search for a cycle. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with the type Map<string, string[]> for the rules. Alternative: The C# example.
GoIdiom
RustIdiomA BTreeMap of rules keeps the names in order, and a BinaryHeap with Reverse or a BTreeSet holds the ready nodes. Alternative: The Go example.
KotlinIdiomA map of rules, a java.util.TreeSet or sortedSetOf for the ready nodes, and a recursive search for a cycle. Alternative: The Java example.
SQLIdiomA table of edges and a recursive common table expression find the depth of each node, which gives the waves. A cycle needs a guard in the recursive query. Alternative: The Python example.
BashIdiomThe tsort utility of POSIX writes a topological order of the pairs in its input. Alternative: The Python example.
PowerShellIdiomHashtables for the rules and the counts, as in the C# example. Alternative: The C# example.
HTMLDoes not applyMarkup has no graph of steps.
CSSDoes not applyStyle rules have no graph of steps.
Regular expressionsDoes not applyA pattern has no graph of steps.

The examples use the graph of a small C program with a parser. A parser generator makes parse.c and parse.h from grammar.y, and app links three object files. Each example finds a topological order with Kahn's method, groups the targets into waves for a parallel build, and searches for a cycle. Then it adds the edge "lex.h needs lex.o", which makes a cycle. Kahn's method then orders only 6 of the 10 nodes, and the search prints the cycle. To give the same order in each language, the examples take the ready node with the smallest name first.

PythonGitHub
# A build graph: a topological order, the waves of a parallel build, and a cycle check.
import heapq

RULES = {
    "app": ["main.o", "parse.o", "lex.o"],
    "main.o": ["main.c", "parse.h"],
    "parse.o": ["parse.c", "parse.h", "lex.h"],
    "lex.o": ["lex.c", "lex.h"],
    "parse.c": ["grammar.y"],
    "parse.h": ["grammar.y"],
}


def nodes(rules):
    names = set(rules)
    for deps in rules.values():
        names.update(deps)
    return sorted(names)


def topological_order(rules):
    # Kahn's algorithm: a node is ready when all its dependencies are done.
    waiting = {n: len(rules.get(n, [])) for n in nodes(rules)}
    users = {n: [] for n in waiting}
    for target, deps in rules.items():
        for dep in deps:
            users[dep].append(target)
    ready = [n for n, count in waiting.items() if count == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        n = heapq.heappop(ready)
        order.append(n)
        for user in users[n]:
            waiting[user] -= 1
            if waiting[user] == 0:
                heapq.heappush(ready, user)
    return order


def waves(rules):
    level = {}
    for n in topological_order(rules):
        deps = rules.get(n, [])
        level[n] = 1 + max(level[d] for d in deps) if deps else 0
    out = {}
    for n, k in level.items():
        if k > 0:
            out.setdefault(k, []).append(n)
    return [sorted(out[k]) for k in sorted(out)]


def find_cycle(rules):
    state = {}  # absent: not seen, 1: on the path, 2: done
    path = []

    def visit(n):
        state[n] = 1
        path.append(n)
        for dep in rules.get(n, []):
            if state.get(dep) == 1:
                return path[path.index(dep):] + [dep]
            if dep not in state:
                found = visit(dep)
                if found:
                    return found
        path.pop()
        state[n] = 2
        return None

    for n in nodes(rules):
        if n not in state:
            found = visit(n)
            if found:
                return found
    return None


print("order:", " ".join(topological_order(RULES)))
for i, wave in enumerate(waves(RULES), 1):
    print("wave " + str(i) + ":", " ".join(wave))
found = find_cycle(RULES)
print("cycle:", " -> ".join(found) if found else "none")
bad = dict(RULES, **{"lex.h": ["lex.o"]})
print("after lex.h <- lex.o:")
print("order:", " ".join(topological_order(bad)), "(" + str(len(topological_order(bad))) + " of " + str(len(nodes(bad))) + " nodes)")
print("cycle:", " -> ".join(find_cycle(bad)))
Output
order: grammar.y lex.c lex.h lex.o main.c parse.c parse.h main.o parse.o app
wave 1: lex.o parse.c parse.h
wave 2: main.o parse.o
wave 3: app
cycle: none
after lex.h <- lex.o:
order: grammar.y lex.c main.c parse.c parse.h main.o (6 of 10 nodes)
cycle: lex.h -> lex.o -> lex.h
  • Verdict: idiom. A dict maps each target to the list of its dependencies, and heapq keeps the ready nodes, so the node with the smallest name comes out first.
  • waves gives each node a level: 0 for an input, and one more than the deepest dependency for a target. The targets with the same level form one wave.
  • find_cycle marks a node 1 while it is on the current path and 2 when it is done. An edge to a node marked 1 closes a cycle.
JavaGitHub
// A build graph: a topological order, the waves of a parallel build, and a cycle check.
import java.util.*;

public class Main {
    static final Map<String, List<String>> RULES = Map.of(
        "app", List.of("main.o", "parse.o", "lex.o"),
        "main.o", List.of("main.c", "parse.h"),
        "parse.o", List.of("parse.c", "parse.h", "lex.h"),
        "lex.o", List.of("lex.c", "lex.h"),
        "parse.c", List.of("grammar.y"),
        "parse.h", List.of("grammar.y"));

    static SortedSet<String> nodes(Map<String, List<String>> rules) {
        SortedSet<String> names = new TreeSet<>(rules.keySet());
        rules.values().forEach(names::addAll);
        return names;
    }

    // Kahn's algorithm: a node is ready when all its dependencies are done.
    static List<String> topologicalOrder(Map<String, List<String>> rules) {
        Map<String, Integer> waiting = new HashMap<>();
        Map<String, List<String>> users = new HashMap<>();
        TreeSet<String> ready = new TreeSet<>();
        for (String n : nodes(rules)) {
            waiting.put(n, rules.getOrDefault(n, List.of()).size());
            users.put(n, new ArrayList<>());
            if (waiting.get(n) == 0) {
                ready.add(n);
            }
        }
        rules.forEach((target, deps) -> deps.forEach(dep -> users.get(dep).add(target)));
        List<String> order = new ArrayList<>();
        while (!ready.isEmpty()) {
            String n = ready.pollFirst();
            order.add(n);
            for (String user : users.get(n)) {
                if (waiting.merge(user, -1, Integer::sum) == 0) {
                    ready.add(user);
                }
            }
        }
        return order;
    }

    static List<List<String>> waves(Map<String, List<String>> rules) {
        Map<String, Integer> level = new HashMap<>();
        TreeMap<Integer, List<String>> out = new TreeMap<>();
        for (String n : topologicalOrder(rules)) {
            int k = 0;
            for (String dep : rules.getOrDefault(n, List.of())) {
                k = Math.max(k, level.get(dep) + 1);
            }
            level.put(n, k);
            if (k > 0) {
                out.computeIfAbsent(k, x -> new ArrayList<>()).add(n);
            }
        }
        List<List<String>> result = new ArrayList<>();
        for (List<String> wave : out.values()) {
            Collections.sort(wave);
            result.add(wave);
        }
        return result;
    }

    static List<String> findCycle(Map<String, List<String>> rules) {
        Map<String, Integer> state = new HashMap<>();
        Deque<String> path = new ArrayDeque<>();
        for (String n : nodes(rules)) {
            if (!state.containsKey(n)) {
                List<String> found = visit(n, rules, state, path);
                if (found != null) {
                    return found;
                }
            }
        }
        return null;
    }

    static List<String> visit(String n, Map<String, List<String>> rules,
                              Map<String, Integer> state, Deque<String> path) {
        state.put(n, 1);
        path.addLast(n);
        for (String dep : rules.getOrDefault(n, List.of())) {
            if (state.getOrDefault(dep, 0) == 1) {
                List<String> list = new ArrayList<>(path);
                List<String> cycle = new ArrayList<>(list.subList(list.indexOf(dep), list.size()));
                cycle.add(dep);
                return cycle;
            }
            if (!state.containsKey(dep)) {
                List<String> found = visit(dep, rules, state, path);
                if (found != null) {
                    return found;
                }
            }
        }
        path.removeLast();
        state.put(n, 2);
        return null;
    }

    public static void main(String[] args) {
        System.out.println("order: " + String.join(" ", topologicalOrder(RULES)));
        List<List<String>> waves = waves(RULES);
        for (int i = 0; i < waves.size(); i++) {
            System.out.println("wave " + (i + 1) + ": " + String.join(" ", waves.get(i)));
        }
        List<String> found = findCycle(RULES);
        System.out.println("cycle: " + (found == null ? "none" : String.join(" -> ", found)));
        Map<String, List<String>> bad = new HashMap<>(RULES);
        bad.put("lex.h", List.of("lex.o"));
        System.out.println("after lex.h <- lex.o:");
        List<String> order = topologicalOrder(bad);
        System.out.println("order: " + String.join(" ", order) + " (" + order.size() + " of " + nodes(bad).size() + " nodes)");
        System.out.println("cycle: " + String.join(" -> ", findCycle(bad)));
    }
}
Output
order: grammar.y lex.c lex.h lex.o main.c parse.c parse.h main.o parse.o app
wave 1: lex.o parse.c parse.h
wave 2: main.o parse.o
wave 3: app
cycle: none
after lex.h <- lex.o:
order: grammar.y lex.c main.c parse.c parse.h main.o (6 of 10 nodes)
cycle: lex.h -> lex.o -> lex.h
  • Verdict: idiom. Map.of holds the rules, and a TreeSet holds the ready nodes, so pollFirst gives the node with the smallest name.
  • waiting.merge(user, -1, Integer::sum) lowers the count and returns the lowered count in one call.
  • The search keeps the current path in an ArrayDeque and copies it to a list to cut out the cycle.
// A build graph: a topological order, the waves of a parallel build, and a cycle check.
var rules = new Dictionary<string, string[]>
{
    ["app"] = ["main.o", "parse.o", "lex.o"],
    ["main.o"] = ["main.c", "parse.h"],
    ["parse.o"] = ["parse.c", "parse.h", "lex.h"],
    ["lex.o"] = ["lex.c", "lex.h"],
    ["parse.c"] = ["grammar.y"],
    ["parse.h"] = ["grammar.y"],
};

SortedSet<string> Nodes(Dictionary<string, string[]> r) =>
    new(r.Keys.Concat(r.Values.SelectMany(deps => deps)), StringComparer.Ordinal);

string[] DepsOf(Dictionary<string, string[]> r, string n) => r.TryGetValue(n, out var d) ? d : [];

// Kahn's algorithm: a node is ready when all its dependencies are done.
List<string> TopologicalOrder(Dictionary<string, string[]> r)
{
    var waiting = new Dictionary<string, int>();
    var users = new Dictionary<string, List<string>>();
    var ready = new SortedSet<string>(StringComparer.Ordinal);
    foreach (var n in Nodes(r))
    {
        waiting[n] = DepsOf(r, n).Length;
        users[n] = [];
        if (waiting[n] == 0)
        {
            ready.Add(n);
        }
    }
    foreach (var (target, deps) in r)
    {
        foreach (var dep in deps)
        {
            users[dep].Add(target);
        }
    }
    var order = new List<string>();
    while (ready.Count > 0)
    {
        var n = ready.Min!;
        ready.Remove(n);
        order.Add(n);
        foreach (var user in users[n])
        {
            if (--waiting[user] == 0)
            {
                ready.Add(user);
            }
        }
    }
    return order;
}

List<List<string>> Waves(Dictionary<string, string[]> r)
{
    var level = new Dictionary<string, int>();
    var output = new SortedDictionary<int, List<string>>();
    foreach (var n in TopologicalOrder(r))
    {
        int k = DepsOf(r, n).Select(dep => level[dep] + 1).DefaultIfEmpty(0).Max();
        level[n] = k;
        if (k > 0)
        {
            if (!output.ContainsKey(k))
            {
                output[k] = [];
            }
            output[k].Add(n);
        }
    }
    return output.Values.Select(w => w.Order(StringComparer.Ordinal).ToList()).ToList();
}

List<string>? FindCycle(Dictionary<string, string[]> r)
{
    var state = new Dictionary<string, int>();
    var path = new List<string>();

    List<string>? Visit(string n)
    {
        state[n] = 1;
        path.Add(n);
        foreach (var dep in DepsOf(r, n))
        {
            if (state.GetValueOrDefault(dep) == 1)
            {
                return [.. path.Skip(path.IndexOf(dep)), dep];
            }
            if (!state.ContainsKey(dep) && Visit(dep) is { } found)
            {
                return found;
            }
        }
        path.RemoveAt(path.Count - 1);
        state[n] = 2;
        return null;
    }

    foreach (var n in Nodes(r))
    {
        if (!state.ContainsKey(n) && Visit(n) is { } found)
        {
            return found;
        }
    }
    return null;
}

Console.WriteLine("order: " + string.Join(" ", TopologicalOrder(rules)));
var waves = Waves(rules);
for (int i = 0; i < waves.Count; i++)
{
    Console.WriteLine($"wave {i + 1}: {string.Join(" ", waves[i])}");
}
var none = FindCycle(rules);
Console.WriteLine("cycle: " + (none is null ? "none" : string.Join(" -> ", none)));
var bad = new Dictionary<string, string[]>(rules) { ["lex.h"] = ["lex.o"] };
Console.WriteLine("after lex.h <- lex.o:");
var order = TopologicalOrder(bad);
Console.WriteLine($"order: {string.Join(" ", order)} ({order.Count} of {Nodes(bad).Count} nodes)");
Console.WriteLine("cycle: " + string.Join(" -> ", FindCycle(bad)!));
Output
order: grammar.y lex.c lex.h lex.o main.c parse.c parse.h main.o parse.o app
wave 1: lex.o parse.c parse.h
wave 2: main.o parse.o
wave 3: app
cycle: none
after lex.h <- lex.o:
order: grammar.y lex.c main.c parse.c parse.h main.o (6 of 10 nodes)
cycle: lex.h -> lex.o -> lex.h
  • Verdict: idiom. A Dictionary<string, string[]> holds the rules, and a SortedSet with StringComparer.Ordinal holds the ready nodes, so Min gives the node with the smallest name.
  • Waves computes each level with LINQ: Select gives the levels of the dependencies plus one, and DefaultIfEmpty(0).Max() gives 0 for an input.
  • Visit is a local function inside FindCycle, and is { } found tests the result for null and names it in one step.
// A build graph: a topological order, the waves of a parallel build, and a cycle check.
package main

import (
	"fmt"
	"slices"
	"strings"
)

var rules = map[string][]string{
	"app":     {"main.o", "parse.o", "lex.o"},
	"main.o":  {"main.c", "parse.h"},
	"parse.o": {"parse.c", "parse.h", "lex.h"},
	"lex.o":   {"lex.c", "lex.h"},
	"parse.c": {"grammar.y"},
	"parse.h": {"grammar.y"},
}

func nodes(rules map[string][]string) []string {
	seen := map[string]bool{}
	for target, deps := range rules {
		seen[target] = true
		for _, dep := range deps {
			seen[dep] = true
		}
	}
	var names []string
	for n := range seen {
		names = append(names, n)
	}
	slices.Sort(names)
	return names
}

// topologicalOrder uses Kahn's algorithm: a node is ready when all its dependencies are done.
func topologicalOrder(rules map[string][]string) []string {
	waiting := map[string]int{}
	users := map[string][]string{}
	var ready []string
	for _, n := range nodes(rules) {
		waiting[n] = len(rules[n])
		if waiting[n] == 0 {
			ready = append(ready, n)
		}
	}
	for target, deps := range rules {
		for _, dep := range deps {
			users[dep] = append(users[dep], target)
		}
	}
	var order []string
	for len(ready) > 0 {
		slices.Sort(ready)
		n := ready[0]
		ready = ready[1:]
		order = append(order, n)
		for _, user := range users[n] {
			waiting[user]--
			if waiting[user] == 0 {
				ready = append(ready, user)
			}
		}
	}
	return order
}

func waves(rules map[string][]string) [][]string {
	level := map[string]int{}
	var out [][]string
	for _, n := range topologicalOrder(rules) {
		for _, dep := range rules[n] {
			level[n] = max(level[n], level[dep]+1)
		}
		if k := level[n]; k > 0 {
			for len(out) < k {
				out = append(out, nil)
			}
			out[k-1] = append(out[k-1], n)
		}
	}
	for _, wave := range out {
		slices.Sort(wave)
	}
	return out
}

func findCycle(rules map[string][]string) []string {
	state := map[string]int{}
	var path []string
	var visit func(n string) []string
	visit = func(n string) []string {
		state[n] = 1
		path = append(path, n)
		for _, dep := range rules[n] {
			if state[dep] == 1 {
				i := slices.Index(path, dep)
				return append(slices.Clone(path[i:]), dep)
			}
			if state[dep] == 0 {
				if found := visit(dep); found != nil {
					return found
				}
			}
		}
		path = path[:len(path)-1]
		state[n] = 2
		return nil
	}
	for _, n := range nodes(rules) {
		if state[n] == 0 {
			if found := visit(n); found != nil {
				return found
			}
		}
	}
	return nil
}

func main() {
	fmt.Println("order:", strings.Join(topologicalOrder(rules), " "))
	for i, wave := range waves(rules) {
		fmt.Printf("wave %d: %s\n", i+1, strings.Join(wave, " "))
	}
	if found := findCycle(rules); found == nil {
		fmt.Println("cycle: none")
	}
	bad := map[string][]string{"lex.h": {"lex.o"}}
	for k, v := range rules {
		bad[k] = v
	}
	fmt.Println("after lex.h <- lex.o:")
	order := topologicalOrder(bad)
	fmt.Printf("order: %s (%d of %d nodes)\n", strings.Join(order, " "), len(order), len(nodes(bad)))
	fmt.Println("cycle:", strings.Join(findCycle(bad), " -> "))
}
Output
order: grammar.y lex.c lex.h lex.o main.c parse.c parse.h main.o parse.o app
wave 1: lex.o parse.c parse.h
wave 2: main.o parse.o
wave 3: app
cycle: none
after lex.h <- lex.o:
order: grammar.y lex.c main.c parse.c parse.h main.o (6 of 10 nodes)
cycle: lex.h -> lex.o -> lex.h
  • Verdict: idiom. A map[string][]string holds the rules. The order of a Go map is not fixed, so nodes sorts the names, and the ready list is sorted before each step.
  • waves reads the nodes in topological order, so the level of each dependency is known before the level of the node that needs it.
  • findCycle is a closure that calls itself, declared with var visit func(n string) []string first. slices.Clone copies the cycle out of the path.
  • Static and dynamic dependencies. Make needs all the dependencies before the build starts, so its graph is static.4 Some build systems find dependencies while the tasks run. In Excel, the formula INDIRECT("A" & C1) depends on a cell whose name is known only after C1 is computed.4 In Shake, a rule can read a file that lists other files, and then depend on each of them.4 A static topological order cannot handle dynamic dependencies. The paper describes two other schedulers for them: a restarting scheduler stops a task that needs a key that is out of date and tries it again later, and a suspending scheduler pauses the task while it builds the key.4
  • Order-only prerequisites. In GNU Make, a normal prerequisite gives an order and a dependency: the prerequisite is built first, and if it is newer, the target is out of date.9 An order-only prerequisite gives only the order. It is built first, but a change to it does not make the target out of date.9 A directory that must exist before files go into it is the usual example.
  • Graphs of targets and graphs of actions. CMake works with high-level targets, such as one library or one executable.3 The build tool that CMake generates works with the individual commands. The two graphs have different sizes, but the same rules apply.
  • Task graphs. In a task-based tool, the graph links tasks, not files. The tool cannot tell if two tasks touch the same file, so it cannot know in general that running them at the same time is safe.10

Pitfalls

  • A missing edge. If a step reads a file that another step writes, but the build file does not have the edge, a serial build can still work by luck, because the steps run in the order of the file. A parallel build then fails at random, or reads a half-written file. The Ninja manual says that underspecified build dependencies result in incorrect builds.8
  • An extra edge. An edge that is not needed makes the graph deeper. The build is still correct, but fewer steps can run in parallel, and a change to the extra dependency rebuilds the target for no reason.
  • One step that writes many files. A parser generator writes parse.c and parse.h in one command. If the build file has two separate rules, a parallel build can run the command two times at the same time. Use the syntax of the tool for a rule with many outputs. In Ninja, a build edge may have many outputs.8
  • A cycle in generated code. A generated header that needs a program that includes the header makes a cycle. Break it with a separate step that generates the header first.
  • Waves are not a schedule. Steps have different durations, so a tool that waits for each wave to finish loses time. A tool starts each step as soon as its own dependencies are done.2

Cost

Kahn's method looks at each node and each edge one time. The paper of 1962 says that a PERT network of 30,000 activities can be ordered in less than one hour of machine time, on the IBM 7090 of that time.5 For a build tool, the cost of the graph is usually small next to the cost of the steps. The cost is in the reading: Bazel parses every BUILD file in the workspace before it builds,2 and each tool must check the inputs before it can start.

Parallel builds trade memory and CPU for time. With n workers, the time of a build is at least the total time of the steps divided by n, and at least the time of the longest path. The Bazel documentation says that parallel steps can give an order of magnitude improvement over building targets one at a time on a multicore machine.2

History

Make uses a static graph and a topological order.4 GNU Make has the -j option for parallel execution,6 and POSIX added -j maxjobs to make in Issue 8, the edition of 2024.7 The paper says that for years Make dominated, but the challenges of scale then drove large firms such as Microsoft, Facebook and Google to develop their own build systems.4 Bazel builds the full graph from the BUILD files of the workspace.2 Ninja leaves the graph to a generator program, and runs it as fast as it can.8 In 2018, Mokhov, Mitchell and Peyton Jones described the order of a build as one choice in the design of a build system, the scheduler, and compared the topological, restarting and suspending schedulers.4

References

  1. GNU make manual (version 4.4.1), 2.3 How make Processes a Makefile, the default goal; rules that the goal does not depend on
  2. Bazel documentation, Artifact-Based Build Systems, the steps of bazel build; parallelism
  3. CMake 3.28.3 documentation source, cmake-buildsystem(7), Introduction; Binary Targets
  4. Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, Build Systems à la Carte, Proceedings of the ACM on Programming Languages 2 (ICFP), Article 79, 2018, 1 Introduction; 2.1 Make; 2.2 Excel; 2.3 Shake; 4.1 The Scheduler (Topological, Restarting, Suspending); 6.2 Parallelism
  5. A. B. Kahn, Topological sorting of large networks, Communications of the ACM 5(11), pages 558 to 562, 1962, abstract
  6. GNU make manual (version 4.4.1), 5.4 Parallel Execution, the -j option; job slots
  7. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), make, SYNOPSIS (-j maxjobs); CHANGE HISTORY, Issue 8
  8. The Ninja build system manual (version 1.13.1), Comparison to Make (builds run in parallel; underspecified dependencies; build edges with many outputs)
  9. GNU make manual (version 4.4.1), 4.3 Types of Prerequisites, normal and order-only prerequisites
  10. Bazel documentation, Task-Based Build Systems, difficulty of parallelizing build steps

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KR9AVG/text.yaml