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}}
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
% 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.
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)
\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
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})
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.
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
\includeonlyaround the wrong chapters changes nothing when one 600-row table owns the time;latexmk -timesays 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.demonever opens the files, so a broken path is invisible and the page breaks you measured were not real. Stamp fast builds withdraftwatermarkand keep the switch in a flag file rather than in the source. - Leaving
samples=1000in a plot drafted at midnight. That is forty times the default work, per curve, per pass. Cache the picture with\tikzexternalizeor take the number back down while drafting. - Waiting for
\timingor\usepackage{fast-draft}to exist. Neither ships in TeX Live:\timingis not a TeX command and there is no package by that name. Use thetimecommand of the shell,latexmk -time, and four lines over\pdfelapsedtime,\XeTeXelapsedtimeoros.clock(). - Deleting
.auxfiles 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\includeonlynow numbers chapters against a stale auxiliary file. - Treating an endless
Label(s) may have changedloop as a tool problem. Something in the document changes the page it sits on — a\pagerefinside its own caption, a package which rewrites content per pass. Find it before raising$max_repeat. - Writing
$pdf_mode = 4for 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
\tracingallinside 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
\todayand unpinned timestamps in a project whose CI caches by hash. Every run differs, the cache never hits, andSOURCE_DATE_EPOCHfixes the PDF header but not the date in the text.
Questions about this lesson
Why is my LaTeX compilation so slow?
\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?
\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?
\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?
How do I make a LaTeX build reproducible?
\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?
\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.
Keep reading
Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.