TExcelTAD
Home › GNU Make & Ninja › Model: A Ninja-style Scheduler

Model: A Ninja-style Scheduler

Ninja's core loop is short: keep a set of ready edges (all inputs built), start ready edges while fewer than N are running and their pool has room, wait for one to finish, mark its outputs done, and move newly unblocked edges to the ready set. This lesson builds that loop in JavaScript, with simulated durations instead of real processes, so you can experiment with -j, pools and scheduling order.

The scheduler

Each edge has outputs, inputs, a duration (as .ninja_log would record it) and optionally a pool. The simulation advances a virtual clock from one job completion to the next, and prints Ninja-style status lines.

js · try it yourself
const edges = [
  { out: 'lexer.o', ins: ['lexer.c'], secs: 2, rule: 'CC' },
  { out: 'eval.o', ins: ['eval.c'], secs: 3, rule: 'CC' },
  { out: 'util.o', ins: ['util.c'], secs: 1, rule: 'CC' },
  { out: 'main.o', ins: ['main.c'], secs: 1, rule: 'CC' },
  { out: 'gen/parser.c', ins: ['grammar.y'], secs: 2, rule: 'YACC' },
  { out: 'parser.o', ins: ['gen/parser.c'], secs: 6, rule: 'CC' },
  { out: 'libcalc.so', ins: ['parser.o', 'lexer.o', 'eval.o', 'util.o'], secs: 3, rule: 'LINK', pool: 'link' },
  { out: 'calc', ins: ['main.o', 'libcalc.so'], secs: 2, rule: 'LINK', pool: 'link' },
  { out: 'calc_test', ins: ['main.o', 'libcalc.so'], secs: 2, rule: 'LINK', pool: 'link' },
];
const pools = { link: 1 };                         // like: pool link / depth = 1

// Longest remaining path from each edge to the end of the build (using the logged durations).
function criticalPath() {
  const memo = new Map();
  const cp = (e) => {
    if (!memo.has(e.out)) {
      const users = edges.filter((u) => u.ins.includes(e.out));
      memo.set(e.out, e.secs + Math.max(0, ...users.map(cp)));
    }
    return memo.get(e.out);
  };
  edges.forEach(cp);
  return memo;
}

function build(jobs, policy, verbose) {
  const built = new Set(['grammar.y', 'lexer.c', 'eval.c', 'util.c', 'main.c']);  // sources
  const prio = criticalPath();
  const running = [];
  const waiting = new Set(edges);
  let t = 0, done = 0;
  const inPool = (p) => running.filter((r) => r.e.pool === p).length;
  while (waiting.size || running.length) {
    let ready = [...waiting].filter((e) => e.ins.every((i) => built.has(i)));
    if (policy === 'critical-path') ready.sort((a, b) => prio.get(b.out) - prio.get(a.out));
    for (const e of ready) {
      if (running.length >= jobs) break;
      if (e.pool && inPool(e.pool) >= pools[e.pool]) continue;   // pool full: skip, try the next
      waiting.delete(e);
      running.push({ e, end: t + e.secs });
    }
    running.sort((a, b) => a.end - b.end);
    const { e, end } = running.shift();
    t = end;
    built.add(e.out);
    if (verbose) console.log(`t=${String(t).padStart(2)}s [${++done}/${edges.length}] ${e.rule} ${e.out}`);
  }
  return t;
}

build(2, 'file-order', true);
for (const policy of ['file-order', 'critical-path']) {
  const times = [1, 2, 4, 8].map((j) => `-j${j}: ${build(j, policy, false)}s`);
  console.log(`${policy.padEnd(13)} ${times.join('  ')}`);
}
console.log('critical path:', criticalPath().get('gen/parser.c'), 's (YACC -> CC parser.o -> LINK libcalc.so -> LINK calc)');
t= 2s [1/9] CC lexer.o
t= 3s [2/9] CC eval.o
t= 3s [3/9] CC util.o
t= 4s [4/9] CC main.o
t= 5s [5/9] YACC gen/parser.c
t=11s [6/9] CC parser.o
t=14s [7/9] LINK libcalc.so
t=16s [8/9] LINK calc
t=18s [9/9] LINK calc_test
file-order    -j1: 22s  -j2: 18s  -j4: 16s  -j8: 15s
critical-path -j1: 22s  -j2: 15s  -j4: 15s  -j8: 15s
critical path: 13 s (YACC -> CC parser.o -> LINK libcalc.so -> LINK calc)

Reading the results

  • The pool: calc and calc_test both become ready at t=11, but the link pool has depth 1, so they run one after the other even at -j8. That's why no -j beats 15 seconds here, although the critical path is only 13: the second link has to wait. Try pools = { link: 2 } and run again.
  • Scheduling order: the generated parser is listed after the small compiles, so in file order YACC starts only at t=3 (it finishes at t=5 in the trace), and the longest chain (YACC → parser.o → libcalc.so → calc) starts late. The critical-path policy starts it first and finishes 3 seconds sooner at -j2. With more cores the gap shrinks (16 against 15 seconds at -j4) and at -j8 every ready job starts at once, so the order stops mattering.
  • [done/total]: Ninja's status line counts finished edges out of all edges it plans to run, exactly like the model.

Newer Ninja releases use the durations recorded in .ninja_log to give jobs on the longest remaining path priority among the ready ones, the "critical-path" policy above. On the first build, with no log yet, they fall back to file order. Make has no such information and always uses the written order of prerequisites.

A second experiment: what -j costs in memory

Parallelism isn't free. Each compiler process needs memory, and C++ compiles of template-heavy code can need gigabytes. This model finds the largest -j that stays within a memory budget, for jobs that each need a given amount of RAM at peak:

js · try it yourself
const compileMB = 900, linkMB = 3500, ramMB = 16000, reserveMB = 2000;
for (const links of [0, 1, 2]) {
  const free = ramMB - reserveMB - links * linkMB;
  const j = Math.max(1, Math.floor(free / compileMB));
  console.log(`${links} link(s) running -> at most -j${j} compiles fit in ${free} MB`);
}
0 link(s) running -> at most -j15 compiles fit in 14000 MB
1 link(s) running -> at most -j11 compiles fit in 10500 MB
2 link(s) running -> at most -j7 compiles fit in 7000 MB

That's the reasoning behind a link pool of depth 1 or 2 in large projects (CMake: set_property(GLOBAL PROPERTY JOB_POOLS link_pool=1) plus CMAKE_JOB_POOL_LINK), and behind -l (load limit) in shared CI machines. When a build machine starts swapping, a lower -j is often faster.

Test yourself

In the model, why does -j8 not beat 15 seconds?

  1. The model ignores -j
  2. The link pool (depth 1) serialises the two final links
  3. Compiles are always serial
  4. Ninja caps at 4 jobs

What information lets recent Ninja versions prioritise the critical path?

  1. Compiler flags
  2. Command durations recorded in .ninja_log from earlier builds
  3. File sizes
  4. The order of default statements

A build machine starts swapping at -j32. What's the usual fix?

  1. Increase -j
  2. Lower -j, and limit memory-heavy steps like links with a pool
  3. Use make -k
  4. Disable header dependencies