Stage 6 · Production, macros and packages 48 / 48 ≈ 24 min read

Speeding Up LaTeX Builds and Debugging a Broken Document

A slow build and a broken build are the same skill: find out where the time or the failure actually is, then change that and nothing else. TeX sets a page of text in single-digit milliseconds, so a ninety-second build is a document asking for expensive work repeatedly — plots resampled on every pass, a table rebuilt from tokens three times, more passes than the content needs. This page covers the instruments and the switches: reading the per-rule timing output of latexmk, what a hand-typed tabular and a pgfplots plot with samples=1000 really cost, the draft and demo switches and what each one stops doing, the tracing counters which show you an expansion or a shipped box, the bisection that turns a 4000-line failure into a nine-line one, and the version and timestamp work which makes a build reproducible in CI.

    Measure first: what latexmk -time actually prints

    Add -time to any latexmk call and it reports per rule instead of per hope. The lines are fixed and worth learning: one 'pdflatex': time = 24.87 per rule executed, with rule names taken from the tool — pdflatex, xelatex, xdvipdfmx, lualatex, biber, makeindex, view — followed by Processing time = ..., of which invoked processes = ..., other = ..., Elapsed clock time = ... and Number of rules run = N for each invocation, and Grand total processing time = ... plus Total number of rules run = ... at the end. The gap between processing time and invoked processes is the overhead of latexmk itself, which is normally noise and occasionally the whole story.

    Two readings of the same block answer most questions. Three 'xelatex' lines at 25 seconds each say that the content is expensive and the passes are the multiplier; one line at 75 seconds says that a single construction inside a single run owns the cost, so start bisecting rather than tuning. Under XeLaTeX you will see xelatex and xdvipdfmx as two rules, because latexmk runs xelatex -no-pdf and converts the resulting .xdv separately — the XeLaTeX total is therefore not the time of one program. On Windows, latexmk falls back to clock time because the child process times are not reliably available, so read the split there as approximate.

    The log supplies the rest without a stopwatch. grep -c "Output written" thesis.log counts the PDF passes you paid for; grep -n "^!" thesis.log counts real errors; grep -c Overfull thesis.log tells you whether a package is busy fighting line breaking; and the presence of Rerun to get cross-references right in the final pass means that the loop never finished. Read those five before changing anything, because applying \includeonly to a document whose time goes into one 600-row table is the most common wasted afternoon in this trade.

    One myth to retire on the way in: \timing is not a LaTeX or TeX command, whatever a blog post asserts, and there is no fast-draft package in TeX Live either, so tlmgr info fast-draft comes back empty. The machinery to write both exists in a few lines: the elapsed-time registers of the engines, covered below, and a flag file plus twelve lines of preamble for the fast mode. The first listing implements a \starttimer/\stoptimer pair under all three engines, which makes the name you were searching for a macro you own rather than one you are missing.

    t_{\mathrm{build}} = \sum_{p=1}^{P} t_{p} + t_{\mathrm{bib}} + t_{\mathrm{convert}}
    t_{\mathrm{build}} = \sum_{p=1}^{P} t_{p} + t_{\mathrm{bib}} + t_{\mathrm{convert}}
    Build time waterfall: the per-rule output of latexmk -time for one thesis build, then where the seconds inside a single pass go ILLUSTRATIVE SHAPE — MEASURE YOUR OWN BEFORE MOVING ANYTHING latexmk -time: seconds per rule, 75.4 s total 'xelatex' pass 1 24.9 'xelatex' pass 2 24.6 'xelatex' pass 3 24.8 'xdvipdfmx' 0.7 'biber' 0.4 three engine passes, not one: content is expensive, and the multiplier is yours too Inside one 24.9 s pass plots: pgfplots + TikZ redrawn 11.6 s · samples=1000 tables: 400-row hand tabular 7.4 s · siunitx S columns images read and re-embedded 3.1 s font shaping, protrusion, subsetting 1.8 s The thin bars are what TeX is fast at: 200 pages of ordinary text cost about 1.1 s, which is why the wide bars are the story. \tikzexternalize · samples=25 · trim the table · pre-convert SVG each one removes a named bar from every pass — that is the whole of the arithmetic latexmk -time -g | grep -c "Output written" thesis.log | \includeonly{ch03} Reading the totals: Processing time counts latexmk plus its children; on Windows that split is approximate, since latexmk falls back to clock time.
    One thesis pass, bar by bar, and the switch which removes each bar. Text is the thin bar; measure your own document before trusting this shape.

    What the seconds actually go into

    A tabular is not markup being skimmed. Every cell is TeX scanning tokens, every & closes an alignment entry and every \\ ends a row, so a 400-row by 6-column table is a couple of thousand group openings, box builds and penalty insertions — per pass, with each entry measured once before the column widths are settled. A hand-typed table of that size is the single most common way to add seconds to a thesis build, and it is invisible in the source, because twelve lines copied from a spreadsheet look like nothing at all.

    A pgfplots axis costs more per unit of ink because it is a program rather than a picture. samples is the multiplier: the default is 25 points per curve, and samples=1000 asks for a thousand function evaluations, a thousand coordinate computations in TeX macros, and a thousand points pushed into the input stream to be joined — for every \addplot, on every pass. Take the number back to 25 or 50 while drafting, or stop recomputing altogether: \usetikzlibrary{external} with \tikzexternalize[prefix=tikzcache/] renders each picture once into \jobname-N.pdf and reuses it while the content of that picture is unchanged, at the cost of -shell-escape and a cache directory which must be kept out of the reach of latexmk -c.

    The third family of cost is packages which iterate to satisfy a constraint. tabularx typesets a whole table repeatedly to fit its X columns; longtable iterates on column widths and needs extra passes for its page ranges; siunitx parses every number in an S column in order to align it, which \sisetup{parse-numbers=false} switches off; microtype does protrusion and spacing work which also changes line breaking; tcolorbox with breakable measures a box in order to split it. Each earns its cost when the output depends on it, which is why the drafting answer is to switch it off and the proofing answer is to switch it back on and rebuild from a clean directory.

    Two more entries, in decreasing order of how often they are the real cause. Every \pause in a beamer deck is a full shipout of the whole frame, so five overlay steps are five renders of everything on that slide. And an image included as a PDF containing PDFs, or as a PNG which the engine has to convert, is paid for per pass too — convert once, offline, to a PDF at roughly the size which will be printed, and let the build read bytes instead of drawing them.

    \sum_{i=1}^{400} \sum_{j=1}^{6} w_{ij} x_{ij} \le \sum_{i=1}^{400} \sum_{j=1}^{6} w_{ij}\lvert x_{ij}\rvert
    \sum_{i=1}^{400} \sum_{j=1}^{6} w_{ij} x_{ij} \le \sum_{i=1}^{400} \sum_{j=1}^{6} w_{ij}\lvert x_{ij}\rvert
    % slow.tex — three expensive constructs in one file, each with a switch.
    % Measure the difference instead of believing it:
    %   latexmk -time slow.tex
    %   touch heavy.flag && latexmk -g -time slow.tex
    \documentclass[11pt,a4paper]{article}
    \usepackage{booktabs}
    \usepackage{pgfplots}
    \pgfplotsset{compat=1.18}
    
    \newif\ifheavy
    \IfFileExists{heavy.flag}{\heavytrue}{\heavyfalse}   % scale up with a flag file
    
    \newcount\rowcount
    \newcommand{\maketable}[1]{%
      \rowcount=0
      \begin{tabular}{rrr}
        \toprule
        value & square & cube \\
        \midrule
        \loop
          \number\rowcount &
          \number\numexpr\rowcount*\rowcount\relax &
          \number\numexpr\rowcount*\rowcount*\rowcount\relax \\
          \advance\rowcount by 1
        \ifnum\rowcount<#1 \repeat
        \bottomrule
      \end{tabular}%
    }
    
    \begin{document}
    \section{A generated table}
    Every cell below is built from scratch on every pass: 400 rows times 3 columns
    is 1200 alignment entries, each a token scan, a box and a penalty.
    
    \ifheavy
      \maketable{400}
    \else
      \maketable{40}
    \fi
    
    \section{A plot whose cost is one number}
    \begin{figure}[htbp]
    \centering
    \begin{tikzpicture}
      \begin{axis}[width=0.8\textwidth, xlabel={$x$}, ylabel={$y$}, legend pos=north east]
        \ifheavy
          \addplot[domain=0:360, samples=1000, smooth] {sin(x)};
          \addlegendentry{\texttt{samples=1000}}
        \else
          \addplot[domain=0:360, samples=25] {sin(x)};      % the pgfplots default
          \addlegendentry{\texttt{samples=25}}
        \fi
      \end{axis}
    \end{tikzpicture}
    \caption{One curve: forty times the function evaluations, forty times the
      coordinates pushed into the input stream, once per pass.}
    \end{figure}
    
    \section{What a determinant actually costs}
    Nothing worth arguing about. A 4-by-4 determinant is a few hundred tokens:
    \[
      \det\begin{pmatrix} 2 & 1 & 0 & 0 \\ 1 & 2 & 1 & 0 \\
                          0 & 1 & 2 & 1 \\ 0 & 0 & 1 & 2 \end{pmatrix} = 5 .
    \]
    If your build takes a minute, it is not the maths. It is the plots, the tables,
    the images and the number of passes.
    \end{document}

    draft, final, demo: what each switch actually stops doing

    The class option draft does two separate things: it marks overfull lines with a black rule so that you can see them, and it passes draft on to graphicx, which replaces each image with a framed box carrying the file name. It still opens the file to measure it. \usepackage[demo]{graphicx} is the faster animal: every \includegraphics becomes a fixed-size black box and the file is never touched — which is precisely why it is for drafting only, since a broken path stops being an error and the layout you measured is not the layout which will be printed. In between sits the per-image key \includegraphics[draft]{...}, because graphicx defines draft as a Gin option: one enormous figure can be a box while the rest of the document stays real.

    Because draft and final are the same words at two different levels, the combinations are meaningful and you should pick yours on purpose: \documentclass[draft]{book} with \usepackage[final]{graphicx} gives overfull rules and real pictures, and the reverse gives pictures without marks. Whatever you choose, stamp the result so that nobody submits a fast build — draftwatermark with \SetWatermarkText{FAST BUILD} makes the mistake visible, and \usepackage[draft]{todonotes} keeps notes in the margin without generating its list file.

    There is no fast-draft package to load, so the switch is yours to write, and the version worth having is out of band. Put a flag file beside the source and test it in the preamble — \IfFileExists{fastbuild.flag}{\slimbuildtrue}{\slimbuildfalse} — and let that conditional choose the graphicx option, the sampling of TikZ, \sisetup{parse-numbers=false}, \microtypesetup{activate=false} and whether an appendix environment is skipped at all. The payoff is that fast mode never lives in the file: the build command in your editor becomes touch fastbuild.flag && latexmk -pdf thesis.tex, an accidental commit cannot carry it, and CI, which has no flag, builds the real document by construction. That is strictly better than editing [draft] into \documentclass on a Friday evening.

    For whole regions rather than one construct, \excludecomment{appendixlongtable} from the comment package removes an environment and its contents from the run while leaving the source intact; unlike \iffalse...\fi it does not care about unbalanced braces or verbatim material inside. Keep everything which affects pagination in the fast build unless you have stopped checking page breaks: draft does not move where pages break, demo does.

    % fast.tex — one source, two builds. Flip the switch out of band so it can never
    % be committed by accident:  touch fastbuild.flag   (rm it before proofing)
    \documentclass[11pt,a4paper,twoside]{book}
    
    \newif\ifslimbuild
    \IfFileExists{fastbuild.flag}{\slimbuildtrue}{\slimbuildfalse}
    
    \usepackage{amsmath,amssymb}
    \usepackage{graphicx}
    \ifslimbuild
      % demo: every \includegraphics becomes a fixed-size box and the file is never
      % opened. Fastest of the three modes, and it hides broken paths too.
      \usepackage[demo]{graphicx}
    \else
      \usepackage{graphicx}
    \fi
    
    \usepackage{tikz,pgfplots}
    \pgfplotsset{compat=1.18}
    \ifslimbuild
      % Where caching is possible instead of hiding, cache (-shell-escape needed):
      % \usetikzlibrary{external}\tikzexternalize[prefix=tikzcache/]
      \tikzset{samples=20}          % draft-time sampling; raise it for the proof
    \else
      \tikzset{samples=200}
    \fi
    
    \usepackage{booktabs}
    \usepackage{siunitx}
    \ifslimbuild
      \sisetup{parse-numbers=false} % S columns otherwise re-parse every number
    \fi
    
    \IfFileExists{microtype.sty}{\usepackage{microtype}}{}
    \ifslimbuild
      \microtypesetup{activate=false}   % costs time AND changes line breaks
    \fi
    
    % Notes stay visible without paying for their list file.
    \IfFileExists{todonotes.sty}{\usepackage[draft]{todonotes}}{}
    \ifslimbuild
      \IfFileExists{draftwatermark.sty}{%
        \usepackage{draftwatermark}\SetWatermarkText{FAST BUILD}%
      }{}
    \fi
    
    % Drop a whole region from the run without deleting a line of source.
    \IfFileExists{comment.sty}{%
      \usepackage{comment}%
      \excludecomment{appendixlongtable}%
    }{%
      \newenvironment{appendixlongtable}{}{}%
    }
    
    \begin{document}
    \chapter{Same file, two costs}
    An em dash --- and a quoted ``example'' still work in a fast build, because
    those are input mappings rather than graphics.
    
    \begin{figure}[htbp]
      \centering
      \includegraphics[width=0.6\textwidth]{measurement-fig}
      \caption{In a slim build this is a black box of the stated size.}
    \end{figure}
    
    \begin{appendixlongtable}
      A 900-row table lives here; the environment above is skipped entirely.
    \end{appendixlongtable}
    
    \[
      \sum_{i=1}^{n} x_i^{2} \le \Bigl(\sum_{i=1}^{n} \lvert x_i\rvert\Bigr)^{2}
    \]
    \end{document}

    Passes, the cache, and the decisions latexmk makes for you

    A pass exists because the document cannot know its own cross-references while it is being written: labels are recorded as they are met and read back on the next run, and resolving a number changes a line length, which can move a break, which changes a page number. LaTeX signals the unfinished state with Rerun to get cross-references right, and the test latexmk applies is a match on Rerun to get in the log, together with whether the .aux changed since last time. It caps the loop at $max_repeat = 5. A document which never converges has a real bug — most often a \pageref inside its own caption, or a package which rewrites material on each pass — and raising the cap only hides it.

    For deciding whether to run at all, latexmk keeps .fdb_latexmk: every source, generated file and dependency with its time, size and hash. That database is why a project copied into a container with a skewed clock does not always rebuild from zero, and why touching a file which nothing inputs costs nothing. Its second source of truth is the .fls list written by the -recorder option of the engine — the files genuinely read and genuinely written during the run — and current latexmk has $recorder = 1 on by default, so it parses that list instead of guessing from extensions. Pass -recorder- to turn it off, which is a thing you will want exactly once, while debugging latexmk itself.

    The switches worth having at finger speed: -g forces every rule regardless of the cache, -c removes intermediates and -C also removes the output, -pvc watches and rebuilds on save with $sleep_time between checks (2 seconds by default), $warnings_as_errors or -Werror turns a warning into a failed CI job, and $pdf_mode selects the engine — 1 pdfLaTeX, 2 via dvi and ps, 3 via dvi, 4 LuaLaTeX and 5 XeLaTeX. Those last two are transposed in a great many .latexmkrc files copied off the internet, and the failure mode is polite: the wrong engine runs, the document guards itself with \iftutex, and you get a PDF which is quietly not the one you meant to review.

    Caching below the level of the tool is where the large wins live, and all of it is offloading: \tikzexternalize per picture, SVG converted to PDF by a script rather than by the svg package calling Inkscape inside every build, generated tables committed as generated files, and the bibliography kept out of the loop while you write prose. Note what biber actually costs: not much by itself — it is the extra engine passes after it which hurt, which is why a settled .bbl plus $bibtex_use = 2 beats any clever cache.

    The latexmk cycle: the dependency database decides whether to run, the log decides whether to run again, and the recorder lists what was touched ONE CALL OF latexmk -pdfxe thesis.tex thesis.tex + \include, .bib, cls, sty up to date? .fdb_latexmk: time · size · hash .fls from -recorder paths really read and written xelatex -no-pdf thesis.tex one pass; this is a 'xelatex' rule in -time no change: nothing runs at all skip to the viewer run again? log matches "Rerun to get" · .aux changed · .bbl missing or stale yes: another pass, capped by $max_repeat = 5 latexmk -g forces it anyway no: the document has settled xdvipdfmx -o .xdv to .pdf, a rule of its own biber thesis job name, not the .bib name thesis.pdf then view / print rules, if allowed auxiliary files, and who owns each .aux labels and citations: written this pass, read back on the next one .log the only place the rerun signal exists .fls the recorder list · .fdb_latexmk the cache .bbl the bibliography, produced out of band what -time prints for one cycle 'xelatex': time = 24.87 Processing time = 75.4, of which invoked = 74.9 Elapsed clock time = 78.1 Number of rules run = 5
    One latexmk cycle: what it reads to decide whether to run, what the engine writes back, and where the -time numbers come from.

    Looking inside the run: the tracing counters and the registers

    The instruments come in increasing violence. \typeout{...} writes to the terminal and the log while the document runs and is the right tool for the question did this code path execute. \errmessage{ARRIVED BEFORE THE TABLE} raises an error of your own at a chosen point, which is how you mark boundaries while bisecting. \show\foo and \showthe{\dimen} print a definition or a register value and stop the run so that you can read them; from that prompt h gives help and x continues.

    The tracing family are counters, so they are cheap to switch on around four lines and off again: \tracingmacros=1 logs every macro expansion with the arguments substituted — the definitive answer to what #1 actually received — while \tracingcommands, \tracingrestores, \tracingassigns, \tracingpages, \tracinggroups and \tracingstats cover tokens as they execute, group endings, register changes, page building and memory use. The kernel bundles them for you: \tracingall is defined as \showoverfull\loggingall, where \loggingall sets \tracingmacros=2, \tracingcommands=3, \tracingstats=2 and \errorcontextlines=\maxdimen among others; \tracingnone and \hideoutput are the matching off switches. Run the fire hose on a six-line file.

    For questions about the output rather than the input, the pair is \tracingoutput and \showoutput. The kernel defines \showoutput as \loggingoutput\showoverfull, and \loggingoutput turns on \tracingoutput with \showboxdepth and \showboxbreadth at \maxdimen, so the log holds the full box structure of every shipped page. Two consequences follow from that single definition: the dump is enormous, and \loggingoutput also issues \errorstopmode, so a run which was sailing past warnings now waits for you at the keyboard. The targeted versions are \showbox on one box and \showlists for the current page. Reading a box dump is a skill; the shortcut is to search it for glue and penalty near the material in question, because almost every question of the form why is there a gap here is answered by one of those two.

    For time rather than structure, the registers are per engine and none of them is called \timing. \time is a TeX counter holding minutes since midnight, so \typeout{START \number\time} gives a bracket with one-minute resolution, which is still enough to discover that one chapter owns four minutes. \pdfelapsedtime under pdfTeX and \XeTeXelapsedtime under XeTeX count ticks from the start of the run, so their difference brackets a region finely; under LuaTeX, os.clock() is the same idea in floating point. The first listing wraps all three in \starttimer and \stoptimer, plus a \timed{...} one-shot, guarded by \ifPDFTeX, \ifXeTeX and \ifLuaTeX so that it builds under any engine.

    \underbrace{f \circ f \circ \cdots \circ f}_{k\text{ expansions}}(x)
    \underbrace{f \circ f \circ \cdots \circ f}_{k\text{ expansions}}(x)
    The nesting above is roughly what \tracingmacros=2 prints: every expansion indented under the one which triggered it, with the arguments substituted in. A run which dies deep in a stack becomes readable; the discipline is switching it off again before the log fills the disk.
    % timing.tex — builds with pdflatex, xelatex *and* lualatex.
    %   latexmk -pdf timing.tex ;  then:  grep "\[timing\]" timing.log
    \documentclass[11pt,a4paper]{article}
    \usepackage{iftex}
    \usepackage{amsmath}
    
    % LaTeX has no \timing. The registers which do exist are engine specific:
    %   pdfTeX : \pdfelapsedtime     ticks since the start of the run
    %   XeTeX  : \XeTeXelapsedtime   ditto
    %   LuaTeX : os.clock(), reached through \directlua
    % All three count from process start, so *differences* are what you use.
    \makeatletter
    \newcount\TIMER@mark
    \ifPDFTeX
      \newcommand\starttimer{\global\TIMER@mark=\pdfelapsedtime}
      \newcommand\stoptimer{\typeout{[timing] \the\numexpr\pdfelapsedtime-\TIMER@mark\relax\space ticks}}
    \fi
    \ifXeTeX
      \newcommand\starttimer{\global\TIMER@mark=\XeTeXelapsedtime}
      \newcommand\stoptimer{\typeout{[timing] \the\numexpr\XeTeXelapsedtime-\TIMER@mark\relax\space ticks}}
    \fi
    \ifLuaTeX
      \newcommand\starttimer{\directlua{timer_start()}}
      \newcommand\stoptimer{\directlua{timer_stop()}}
    \fi
    % One-shot wrapper: \timed{<material>} typesets <material> and logs its cost.
    \newcommand\timed[1]{\starttimer #1\stoptimer}
    \makeatother
    
    \ifLuaTeX
    % \directlua sees catcodes, so code which formats text lives inside luacode.
    \usepackage{luacode}
    \begin{luacode*}
      local mark = 0
      function timer_start () mark = os.clock() end
      function timer_stop ()
        tex.write(string.format("[timing] %.3f s elapsed\n", os.clock() - mark))
      end
    \end{luacode*}
    \fi
    
    \begin{document}
    \section{Bracket the suspect region, not the whole file}
    \timed{%
      A paragraph of ordinary text costs almost nothing, and that is the point of
      measuring it: if a whole page logs a handful of ticks, the seconds are
      elsewhere, and the honest next step is a plot, a table or a package.%
    }
    
    \bigskip
    \subsection{An artificial hot spot}
    \timed{%
      \[
        \sum_{n=1}^{200} \frac{1}{n^{2}} < \frac{\pi^{2}}{6},
        \qquad
        \int_{0}^{\infty} e^{-x^{2}}\,\mathrm{d}x = \frac{\sqrt{\pi}}{2}.
      \]%
    }
    
    Read the numbers as an order of magnitude rather than a stopwatch: what matters
    is that one region sits two or three powers above another. For wall-clock
    figures use the \texttt{time} command of your shell, or \texttt{latexmk -time},
    which already prints a per-rule breakdown.
    \end{document}

    Bisecting a document that will not compile

    Make the failure cheap and legible first, because you are about to repeat it a dozen times: -interaction=nonstopmode so that nothing waits on a keypress, -file-line-error so that messages carry file:line, and -halt-on-error if a hopeless run would otherwise type nonsense for two minutes. Then read the first line beginning with ! and ignore everything below it. After the first real error TeX is recovering, and that recovery is what produces the cascade of Missing } inserted and Runaway argument? which makes a long file look catastrophic. Fixing the top one and rebuilding beats reading four screens.

    Then make TeX show its work. \errorcontextlines controls how much context appears under an error, and the LaTeX kernel initialises it to -1, meaning no context at all; \setcounter{errorcontextlines}{20} in the preamble — it is a counter, aliased to the primitive, so the usual interface works — makes TeX print the lines it is reading and the expansion levels it is inside. That single line is frequently the difference between an Undefined control sequence reported at line 1 and knowing which macro of which package expanded into it.

    Then halve, accepting one build per step. If the document is a book with one \include per chapter, \includeonly{ch07} is the bisector, and it keeps numbering and cross-references coherent while it narrows the search. If it is one 4000-line file, cut it mechanically — sed -n '1,1200p' main.tex > half.tex, append \end{document}, build — and keep whichever half still fails. If the failure smells like a package, halve the preamble instead, leaving what any class needs. Twenty-two chapters become five builds; a 4000-line file becomes a nine-line file which fails, and a nine-line failure is usually obvious without any tool. That is the content of k >= log2(n) applied to a document.

    The alternative to deleting is muting: \iffalse...\fi at the TeX level, and \excludecomment{env} at the LaTeX level, the latter being the robust one because its end marker is scanned verbatim and it survives unbalanced braces and verbatim content inside. Two cases where bisection is the wrong tool, both common. If the document builds but is wrong, work backwards from the PDF instead: a ?? is a missing pass or a label out of scope, a dropped column is an unescaped &, a chapter on the left page is openright rather than a bug. And if the failure is machine-specific, skip to the last section, because the difference is not in your source.

    \frac{n}{2^{k}} \le 1 \iff k \ge \lceil \log_{2} n \rceil
    \frac{n}{2^{k}} \le 1 \iff k \ge \lceil \log_{2} n \rceil
    Bisection ladder: halving a failing document with includeonly, a sed line range or half the preamble, log2 n builds deep, with the cutter chosen by document shape STEP 0 — MAKE THE FAILURE CHEAP, LEGIBLE AND REPEATABLE latexmk -pdf -e '$pdflatex="pdflatex -interaction=nonstopmode -file-line-error -halt-on-error %O %S"' thesis.tex nonstopmode so nothing waits on a key · file-line-error so messages say where · halt-on-error so a hopeless run stops early \setcounter{errorcontextlines}{20} the kernel default is -1: TeX shows the error line and no context at all STEP 1 — HALVE, ONE BUILD PER STEP, KEEPING THE HALF THAT STILL FAILS 4000 lines the whole book fails build 1 12 of 22 chapters \includeonly{ch01..ch12} build 2 1900 lines sed -n 1,1900p > half.tex build 3 480 lines one chapter, then half build 4 9 lines cause now visible build 5, read it k builds for n units of input: the ladder is log2, so a 4000-line file is reached in about twelve cuts and a 22-chapter book in five pick the cutter by the shape of the input book with one \include per chapter → \includeonly{...} one long file → sed -n line ranges suspect a package → comment out half the preamble a region to keep but not build → \excludecomment{env} (comment) fallback, brace-sensitive → \iffalse ... \fi what the first ! line tells you to cut Undefined control sequence → cut the preamble in half Missing } inserted → suspect an alignment or a verb Runaway argument? → a token, not a location: \tracingmacros File `x.sty' not found → kpsewhich x.sty, not a bisection Emergency stop → read the line above it and stop on the nine-line file, ask directly: \show\mycommand \showthe\textwidth \errmessage{REACHED HERE} \tracingmacros=1 ... =0 \typeout{... when it builds but is wrong, skip the ladder: work backwards from the PDF — ?? is a missing pass, a dropped column is an unescaped ampersand
    The halving ladder: the tool for each shape of document, and the log families which decide which half to keep.

    Which package, which file, which bytes: version drift and reproducible builds

    A bug which reproduces on one machine and not on another is a version difference far more often than people assume, and the log can settle it in one read. \listfiles at the top of the preamble makes LaTeX write every file it used, with version and date, at the end of the log; diffing two such logs is usually enough to find the culprit as the only line which differs. kpsewhich --all package.sty lists every copy on the box and shows which one wins, which is how a stale tree in your home directory is found. And the .fls file from -recorder is the list of paths which the engine actually read, answering whether the file being input is the file you think you are editing.

    A PDF is not byte-stable by default: it records when it was made in /CreationDate and /ModDate and derives a file identifier from that, so two builds of an unchanged source differ in the trailer even when nothing was edited. pdfTeX, XeTeX and LuaTeX all honour the environment variable SOURCE_DATE_EPOCH, seconds since the Unix epoch, and use it instead of the clock for those dates and that identifier; on TeX Live releases older than 2019 FORCE_SOURCE_DATE=1 was also required, and setting it on a newer install does no harm. Export a fixed value — the commit date is the usual choice — and sha256sum thesis.pdf gives the same answer twice.

    That is not pedantry but infrastructure. With byte-stable output you can cache a build by hash, prove that a regenerated PDF differs for the reason you believe, and archive a submission whose bytes mean something. Two further sources of drift need pinning for the same reason: \today, and any \date{\today}, bake the wall-clock date into the text, so use an explicit date in anything you expect to rebuild; and generated figures carrying their own timestamps — a plot with a date in its footer — reintroduce the whole problem one level up.

    What is left for CI is to stop the floor moving. Cache the TeX Live installation by release year plus a hash of the package list rather than reinstalling per build, pin the image or the installer URL to one release so that a build green today is green next month, and never run tlmgr update --all inside a pipeline which is supposed to be reproducible. Pin the engine next to the release: $pdf_mode in .latexmkrc or an explicit latexmk -pdfxe thesis.tex in the job step, with \RequireTUTeX or \RequirePDFTeX in the source as the thing which complains when the two disagree. Add -time to the build command and the log of every CI run becomes a performance record of your own document, for free.

    The last item in the timing ledger is the one people forget: view and print are rules too, so ask for $view = 'none' in a headless job. And load hyperref last, not for speed but because a destination written in one pass and read in the next is itself a rerun signal — the same reason a \pageref in a caption can keep a build from settling, and a slow build which never converges is a correctness bug wearing a performance costume.

    \mathrm{PDF}_{t_{1}} = \mathrm{PDF}_{t_{2}} \qquad (t_{1} \ne t_{2})
    \mathrm{PDF}_{t_{1}} = \mathrm{PDF}_{t_{2}} \qquad (t_{1} \ne t_{2})
    The equality above holds only once the timestamp is pinned. Two builds of one source at different moments are the same document and different bytes; SOURCE_DATE_EPOCH is what stops those two statements contradicting each other.
    % forensics.tex — the harness which answers "but it builds on my machine".
    %
    % ---- Pin the build in .latexmkrc, in the same directory as the book: ---------
    %   $pdf_mode   = 1;             # 1 pdflatex, 2 dvi->ps->pdf, 3 dvi->pdf,
    %                                # 4 lualatex, 5 xelatex (+ a separate xdvipdfmx rule)
    %   $xelatex    = 'xelatex -no-pdf -interaction=nonstopmode -file-line-error %O %S';
    %   $recorder   = 1;             # already the default: keep the .fls file list
    %   $max_repeat = 3;             # cap the rerun loop (the default is 5)
    %   $bibtex_use = 2;             # run bibtex/biber when the .bbl is out of date
    %   $clean_ext  = 'synctex.gz run.xml';
    %   $warnings_as_errors = 0;     # or pass -Werror in CI only
    %   $view       = 'none';        # never open a viewer in a headless job
    % ---- and in CI: cache the TeX Live tree by release year plus a hash of the
    %      package list, pin the image to one release, and run `latexmk -time -g`
    %      once per commit, so the log of every run is a performance record.
    % -----------------------------------------------------------------------------
    \documentclass[11pt,a4paper]{article}
    
    % Timestamps: SOURCE_DATE_EPOCH in the environment fixes /CreationDate, /ModDate
    % and the file identifier, so two builds of one source give the same bytes.
    % Nothing in the document may print the clock, or the work is undone.
    \usepackage{iftex}
    \listfiles                            % every file and version, at the end of the log
    \setcounter{errorcontextlines}{20}    % the default inside LaTeX is -1 (no context)
    
    \makeatletter
    % Print the environment the build actually ran in: cheaper than guessing later.
    \typeout{=== \jobname: LaTeX \fmtversion}
    \ifPDFTeX  \typeout{=== engine: pdfTeX \the\pdftexversion.\pdftexrevision}\fi
    \ifXeTeX   \typeout{=== engine: XeTeX \the\XeTeXversion\XeTeXrevision}\fi
    \makeatother
    
    \date{2026-03-14}               % explicit: \today is a timestamp in disguise
    \title{Forensics harness}
    \begin{document}
    \maketitle
    \section{Mark the boundaries you want to see in the log}
    \typeout{--- region A begins}
    A short paragraph.
    \typeout{--- region A ends}
    
    % Ask "is this macro still mine?":        \show\section
    % Ask "what is in this register?":        \showthe\textwidth
    % Mark a point while bisecting:           \errmessage{ARRIVED BEFORE THE TABLE}
    % Log every expansion in a region:        \tracingmacros=1 ... \tracingmacros=0
    % Log the box structure of each page:     \showoutput
    %   (which also sets errorstopmode, and floods the log: use it on a small file)
    
    \[
      \oint_{\partial\Sigma} \omega = \iint_{\Sigma} \mathrm{d}\omega
    \]
    \end{document}

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    t_{\mathrm{build}} = \sum_{p=1}^{P} t_{p} + t_{\mathrm{bib}} + t_{\mathrm{convert}}
    \documentclass[11pt,a4paper]{article}
    \documentclass[11pt,a4paper,twoside]{book}
    \frac{n}{2^{k}} \le 1 \iff k \ge \lceil \log_{2} n \rceil

    Common mistakes

    • Optimising before measuring. Adding \includeonly around the wrong chapters changes nothing when one 600-row table owns the time; latexmk -time says which lever has a load on it.
    • Reading the last error in the log. TeX reports the first one and then recovers badly, so the fix is the first ! line and everything below it is noise until that line is gone.
    • Shipping a [draft] or [demo] build. demo never opens the files, so a broken path is invisible and the page breaks you measured were not real. Stamp fast builds with draftwatermark and keep the switch in a flag file rather than in the source.
    • Leaving samples=1000 in a plot drafted at midnight. That is forty times the default work, per curve, per pass. Cache the picture with \tikzexternalize or take the number back down while drafting.
    • Waiting for \timing or \usepackage{fast-draft} to exist. Neither ships in TeX Live: \timing is not a TeX command and there is no package by that name. Use the time command of the shell, latexmk -time, and four lines over \pdfelapsedtime, \XeTeXelapsedtime or os.clock().
    • Deleting .aux files to fix a reference. You have thrown away every resolved label and citation, so the next build needs the full pass cycle, and a leftover \includeonly now numbers chapters against a stale auxiliary file.
    • Treating an endless Label(s) may have changed loop as a tool problem. Something in the document changes the page it sits on — a \pageref inside its own caption, a package which rewrites content per pass. Find it before raising $max_repeat.
    • Writing $pdf_mode = 4 for XeLaTeX because a blog post said so. In latexmk, 4 is LuaLaTeX and 5 is XeLaTeX; the wrong one usually still builds, which is what makes it expensive to notice.
    • Relying on \tracingall inside a thesis. It is a bundle of counters including \errorcontextlines=\maxdimen, and its output is enormous; use it on the nine-line file you bisected to, and switch off with \tracingnone.
    • Leaving \today and unpinned timestamps in a project whose CI caches by hash. Every run differs, the cache never hits, and SOURCE_DATE_EPOCH fixes the PDF header but not the date in the text.

    Questions about this lesson

    Why is my LaTeX compilation so slow?
    Almost always one of four things: plots and TikZ pictures recomputed on every pass, large tables, more passes than the document needs, or a package that iterates to fit something (tabularx, longtable, siunitx S columns, microtype). Establish which one instead of guessing: latexmk -time prints seconds per rule, grep -c "Output written" on the log counts the PDF passes you paid for, and \includeonly or a sed-truncated copy shows whether one file owns the cost. Then externalise the pictures, commit the table as a generated file, lower the sampling while drafting, and let latexmk handle the passes.
    What is the difference between draft and demo in graphicx?
    Both replace images with boxes, and both are implied by the class option draft and overridden by final. draft draws a frame containing the file name and still opens the file to measure it, so the sizes stay honest. demo returns a fixed-size box and never touches the disk, which is faster and also dangerous: a wrong path stops being an error and the layout is no longer the printed one. You can set it per image with \includegraphics[draft]{...}, and \usepackage[draft]{todonotes} is the same idea for margin notes rather than figures.
    How do I debug a LaTeX document that will not compile?
    Make the failure cheap and legible, then halve the input. Run with -interaction=nonstopmode -file-line-error, read the first line that starts with !, and ignore the cascade under it. Set \setcounter{errorcontextlines}{20} to see the reading context and the expansion levels, because the kernel default of -1 shows neither. Then bisect: \includeonly if the book is split by chapter, a sed line range if it is one file, half the preamble if you suspect a package, \excludecomment or \iffalse...\fi to mute a region without deleting it. When the reduced file is nine lines long, the cause is normally visible; use \show on the way if you need to know whose definition a name currently holds.
    What does latexmk do that I cannot do by hand?
    Three things. It records what each run read and wrote, through the -recorder option of the engine (a .fls list, on by default) and a .fdb_latexmk database of times, sizes and hashes, so unchanged documents are not recompiled at all. It decides which rules to run, including biber or bibtex when the auxiliary file asks for it. And it reruns the engine until the log stops saying Rerun to get cross-references right, capped by $max_repeat. You can do all of that by hand, which is a good way to learn and a bad way to work; add -time and you also get the seconds each of those rules took.
    How do I make a LaTeX build reproducible?
    Fix the clock and fix the toolchain. Export SOURCE_DATE_EPOCH to a constant so the PDF dates and the file identifier stop moving (add FORCE_SOURCE_DATE=1 on TeX Live older than 2019), replace \today with an explicit \date{}, and ship fonts and generated figures with the project so that nothing depends on the machine. In CI, pin the TeX Live release instead of updating it, and pin the engine in .latexmkrc. Two identical sha256sum values for two builds of one source is the test that it worked.
    How do I see what a macro expands to, or what is on a page?
    For expansions, bracket the region with \tracingmacros=1 ... \tracingmacros=0: TeX logs every macro it expands with the arguments substituted, which is how you see what #1 actually received. For the assembled output, \showoutput turns on \tracingoutput with the box depth and breadth at maxdimen and dumps the box structure of each shipped page; note that it also switches to errorstopmode, so do not leave it on. \tracingstats reports memory and page usage, \show\foo prints one definition and stops, and \listfiles records every file and version used. \tracingall is everything at once and belongs on a minimal file.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.