阶段 6 · 出版、宏与宏包 48 / 48 ≈ 21 分钟读完

LaTeX 编译提速与排错:时间去哪、开关怎么关、错误怎么二分

构建太慢和构建失败考验的是同一种能力:先查清时间或故障真正落在哪里,然后只动那一处、别的一律不碰。TeX 排一页正文用的是个位数毫秒,所以九十秒的构建说明文档在反复索要昂贵的活——每遍都重算的曲线、从 token 重搭三次的表格、比内容实际需要的更多遍数。这一课给的是仪表和开关:怎么读 latexmk 的逐规则耗时,一份手打表格和一个 samples 拉到一千的绘图究竟值多少秒,草稿模式与演示模式分别不再做什么,能照见一次展开或一只已输出盒子的 tracing 计数器,把四千行的失败压成九行的二分法,以及让构建在 CI 里可复现的版本与时间戳功夫。

    先量再改:latexmk -time 到底印出了什么

    任何一条 latexmk 命令加上 -time,它就不再让你猜,而是按规则逐条报数。格式是固定的,值得记熟:每跑一条规则就有一行 'pdflatex': time = 24.87,规则名直接取自工具本身——pdflatex、xelatex、xdvipdfmx、lualatex、biber、makeindex、view——接着每次调用给出 Processing time = ..., of which invoked processes = ..., other = ...、Elapsed clock time = ... 和 Number of rules run = N,末尾再补 Grand total processing time = ... 与 Total number of rules run = ...。两份合计相减剩下的那道差额,就是 latexmk 自己的开销,通常是可以忽略的噪声,但偶尔它就是全部原因。

    同一块数字有两种读法,多数问题到此就有答案。三行 'xelatex'、每行二十五秒,说明贵的是内容、遍数只是乘数;只有一行却七十五秒,说明代价集中在同一次运行里的某一条构造上,这时该去二分而不是调参。XeLaTeX 下会看到 xelatex 与 xdvipdfmx 拆成两条规则,因为 latexmk 跑的是 xelatex -no-pdf,产出的 .xdv 另外转换,所以 XeLaTeX 的合计并不是单个程序的耗时。Windows 上取不到可靠的子进程时间,latexmk 会退回墙钟时间,那里两组数字只能当近似值读。

    剩下的线索日志里就有,用不着秒表。grep -c "Output written" thesis.log 数的是你付过钱的 PDF 遍数,grep -n "^!" thesis.log 数的是真正的错误,grep -c Overfull thesis.log 告诉你是否有宏包正在跟断行死磕;最后一遍里若还留着 Rerun to get cross-references right,说明循环根本没收敛。动手改之前先把这五个数读一遍,因为「时间其实全花在一张六百行的表上」却去给文档套 \includeonly,是这行最典型的一个被浪费掉的下午。

    进门先破一条谣:\timing 不是 TeX 或 LaTeX 的命令,不管博客里怎么写;TeX Live 里也没有 fast-draft 这个宏包,tlmgr info fast-draft 查回来是空的。可把自己想要的这两样造出来只要几行:引擎自带的运行耗时寄存器(下面会交代),加一个标记文件配十二行导言区就撑起快速模式。第一份清单在三个引擎下都实现了 \starttimer/\stoptimer 这一对,于是你到处找的那个名字成了一条你自己拥有的宏,而不是一条你以为存在却缺失的命令。

    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.
    一篇论文的单遍构建,逐条拆成柱子,以及每根柱子对应的开关。最细的那根才是正文文字;别照搬这张图的形状,先量你自己的文档。

    时间到底花在了什么地方

    别把 tabular 当成只是被扫一眼的标记。每个单元格都是 TeX 在扫描 token,每个 & 收尾一个对齐项,每个 \\ 收尾一行,于是一张四百行六列的表就是几千次组的开启、装箱和罚项插入——而且每一遍都要重来,列宽定下来之前每个对齐项还得先量一次。论文构建多出来的那几秒钟,最常见的来源就是这种手打表格,偏偏它在源码里毫不显眼:从电子表格粘过来的十二行看上去什么也不是。

    pgfplots 的坐标系每单位墨水更贵,因为它是一段程序而不是一张图。samples 就是那个乘数:每条曲线默认取 25 个点,而 samples=1000 要的是上千次函数求值、上千次在 TeX 宏里算坐标,再把上千个点灌进输入流去连线——每个 \addplot 都如此,每一遍都如此。草拟阶段先把这个数退回 25 或 50,或者干脆别重算:\usetikzlibrary{external} 配 \tikzexternalize[prefix=tikzcache/] 会把每幅图只渲染成 \jobname-N.pdf 一次,只要该图内容没变就一直复用,代价是需要 -shell-escape,还多出一个缓存目录,而它必须躲开 latexmk -c 的清理范围。

    第三类开销来自那些为了凑一个约束而反复迭代的宏包。tabularx 要把内容塞进 X 列,于是整张表重排好几遍;longtable 迭代列宽,还为了分页范围额外多跑几遍;siunitx 为了对齐会把 S 列里每个数字都解析一遍,而 \sisetup{parse-numbers=false} 正是关掉这件事;microtype 做的突出与字距调整连断行结果一起改掉;tcolorbox 配上 breakable 是为了拆开一只盒子而先去量它。只要成品确实依赖它们,这份钱就花得值——所以草拟时的答案是关掉,校对时的答案是打开并从干净目录重编一遍。

    还有两项,按它们是真凶的概率由高到低排。beamer 幻灯片里每个 \pause 都是一次整帧的完整输出,所以五步叠层等于把该页上所有东西画五遍。另一项是图片本身:以「PDF 里套 PDF」的形式引入,或者交给引擎现场转换的 PNG,同样每遍都要付钱——离线转换一次,输出成接近实际印刷尺寸的 PDF,让构建去读字节而不是去画图。

    \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:每个开关究竟不再做什么

    文档类选项 draft 同时做两件互不相干的事:用一条黑杠标出超行,让你看得见它们;以及把 draft 转交给 graphicx,于是每张图被换成一个写着文件名的方框——但它仍然会打开文件去量尺寸。\usepackage[demo]{graphicx} 是更快的那一只:每个 \includegraphics 都变成一个定尺寸的黑盒子,文件根本不会被碰。也正因如此它只配待在草拟阶段:路径写错不再是错误,而你量出来的版面也不是将要印出来的那一版。两者之间还有逐图生效的 \includegraphics[draft]{...},因为 graphicx 把 draft 定义成了一个 Gin 选项:单独一张巨图可以先当盒子使,文档其余部分照旧是真图。

    由于 draft 与 final 是同一对词落在两个不同的层级上,它们的组合是有意义的,而且该由你有意挑一个:\documentclass[draft]{book} 配 \usepackage[final]{graphicx} 得到超行黑杠加真实图片,反过来则是真图而不带标记。无论选哪种,都请在成品上盖个戳,免得有人把快速构建交上去——draftwatermark 配 \SetWatermarkText{FAST BUILD} 让这个错误一眼看得见,\usepackage[draft]{todonotes} 则把待办留在页边而不去生成那份清单文件。

    没有 fast-draft 宏包可供加载,所以这个开关得你自己写,而值得写的版本是「带外」的:在源码旁边放一个标记文件,在导言区试探它——\IfFileExists{fastbuild.flag}{\slimbuildtrue}{\slimbuildfalse}——再让这条条件去决定 graphicx 的选项、TikZ 的采样密度、\sisetup{parse-numbers=false}、\microtypesetup{activate=false},以及要不要整个跳过某个附录环境。好处是快速模式从来不住在源文件里:编辑器里的构建命令变成 touch fastbuild.flag && latexmk -pdf thesis.tex,一次误提交带不走它,而没有标记文件的 CI 天生就在编真正的文档。这比周五傍晚把 [draft] 手改进 \documentclass 严格更优。

    要处理的是整块区域而不止一条构造时,comment 宏包的 \excludecomment{appendixlongtable} 能把一个环境连同其内容一起从这次运行里摘掉,源码却一字不动;与 \iffalse...\fi 不同,它不在乎里面有没有配错的花括号或逐字文本。除非你已经打算不再检查分页,否则凡是影响断页的东西都该留在快速构建里:draft 不会挪动页在哪里断开,demo 会。

    % 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}

    遍数、缓存,以及 latexmk 替你拿的主意

    「多跑一遍」这件事的存在,是因为文档在写自己的时候还不认识自己的交叉引用:标签遇到一次记一次,要到下一次运行才被读回来;而一个编号定下来就改变行宽,行宽一动就可能挪走一处断行,页码于是又变了。LaTeX 用 Rerun to get cross-references right 报告没跑完,latexmk 的判据则是在日志里匹配 Rerun to get,再算上 .aux 自上次以来有没有变过,并把循环封顶在 $max_repeat = 5。永远不收敛的文档是真的带着 bug——最常见的是题注里那个 \pageref 指向了自己所在的那一页,或者某个每遍都重写内容的宏包——把上限调高只是把它盖住。

    至于到底要不要跑,latexmk 靠 .fdb_latexmk 判断:每个源文件、生成物和依赖都记着时间、大小与哈希。项目被拷进一个时钟不准的容器时不必从零重来,随手 touch 一个没人 input 的文件一文不花,都是这份数据库的功劳。它的第二个事实来源是引擎 -recorder 选项写出的 .fls 清单——这次运行真正读过、真正写出的是哪些文件——现行的 latexmk 默认 $recorder = 1,因此它去解析那份清单而不是凭扩展名猜。想关掉就传 -recorder-,而这个需求你大概只会用上一次,那就是调试 latexmk 自身的时候。

    下面这些开关值得练到随手就来:-g 无视缓存强制跑完每条规则;-c 清中间产物,-C 连成品一起清;-pvc 守着文件、存盘即重编,两次检查之间歇 $sleep_time(默认 2 秒);$warnings_as_errors 或 -Werror 能把一条警告变成一次失败的 CI 任务;$pdf_mode 负责挑引擎——1 是 pdfLaTeX,2 走 dvi 再 ps,3 走 dvi,4 是 LuaLaTeX,5 是 XeLaTeX。最后这两个数字在从网上抄来的 .latexmkrc 里被写反的次数多到惊人,而它的失败方式又格外客气:跑的是错的引擎,文档用 \iftutex 自己挡了一下,于是你拿到的那份 PDF 一声不响地编成功了,只是它并不是你打算审的那一份。

    真正的大便宜在工具之下那一层的缓存里,而它的全部手段都是把活外包出去:每幅图各自 \tikzexternalize;SVG 用脚本先转成 PDF,而不是让 svg 宏包在每次构建里去叫 Inkscape;生成的表格就当作生成文件提交进仓库;写正文的那段时间把参考文献整个请出循环。顺便看清 biber 实际花的是多少:它自己并不贵——疼的是它之后额外那几遍引擎运行——所以一份已经定稿的 .bbl 配 $bibtex_use = 2,胜过任何精巧的缓存。

    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
    latexmk 的一整圈:它读什么来判断要不要跑、引擎又往回写些什么,以及 -time 那些数字是从哪一步冒出来的。

    往运行内部看:tracing 计数器与那些寄存器

    这些仪表按破坏力从小到大排列。\typeout{...} 在文档运行途中往终端和日志里写字,用来回答这段代码到底跑过没有正合适。\errmessage{ARRIVED BEFORE THE TABLE} 在你选定的位置抛出一个自己的错误,二分的时候就是靠它插路标。\show\foo 与 \showthe{\dimen} 打出一条定义或一个寄存器的值并且停下等你读;在这个提示下按 h 求助,按 x 继续。

    tracing 这一族全都是计数器,所以只对四行开、完事就关,成本很低:\tracingmacros=1 把每一次宏展开连同代入实参后的结果一起记进日志——#1 究竟收到了什么,这是最权威的答案;而 \tracingcommands、\tracingrestores、\tracingassigns、\tracingpages、\tracinggroups、\tracingstats 分别管 token 的执行、组的结束、寄存器的改动、建页过程和内存占用。内核替你打了包:\tracingall 的定义是 \showoverfull\loggingall,其中的 \loggingall 会设下 \tracingmacros=2、\tracingcommands=3、\tracingstats=2、\errorcontextlines=\maxdimen 等等;配套关掉的开关是 \tracingnone 和 \hideoutput。这条消防水管请只对着一个六行的文件开。

    要问的是产出而不是输入,配对的就是 \tracingoutput 与 \showoutput。内核把 \showoutput 定义成 \loggingoutput\showoverfull,而 \loggingoutput 打开 \tracingoutput 并把 \showboxdepth 和 \showboxbreadth 设到 \maxdimen,于是日志里躺着每一页已输出内容的完整盒结构。这一条定义直接带来两个后果:dump 大得吓人,而且 \loggingoutput 顺手执行了 \errorstopmode,于是一路无视警告往前跑的构建现在停在键盘前等你按键。定点版本是对某一只盒子用 \showbox、对当前页用 \showlists。读盒结构的 dump 是一门手艺,捷径是在相关材料附近搜 glue 和 penalty,因为几乎所有这里为什么多出一道空隙式的问题,答案都在这两者之中。

    换成关心时间而不是结构,寄存器就得按引擎来分,而且没有一个叫 \timing。\time 是个 TeX 计数器,存的是自零点起的分钟数,所以 \typeout{START \number\time} 给你一个精度到分钟的区间——可这也足够让你发现某一章独占四分钟。pdfTeX 下的 \pdfelapsedtime 与 XeTeX 下的 \XeTeXelapsedtime 从进程启动开始数刻度,两者相减就能以细粒度把一段区域夹住;LuaTeX 下同一个想法由 os.clock() 以浮点形式提供。第一份清单把三者统一包进 \starttimer 与 \stoptimer,另附一个一次性的 \timed{...},外面用 \ifPDFTeX、\ifXeTeX、\ifLuaTeX 分流,所以任何引擎都编得动。

    \underbrace{f \circ f \circ \cdots \circ f}_{k\text{ expansions}}(x)
    \underbrace{f \circ f \circ \cdots \circ f}_{k\text{ expansions}}(x)
    上面那种层层缩进的写法,大致就是 \tracingmacros=2 印出来的样子:每次展开都缩进在触发它的那次下面,实参也已经代入。一个在栈深处死掉的运行因此变得可读,要守的纪律是在日志撑爆磁盘之前把它关掉。
    % 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}

    把编不过的文档对半切

    先让失败变得又便宜又清楚,因为你接下来要把它重复十几遍:-interaction=nonstopmode 让没有任何东西在等你按键,-file-line-error 让消息带上 file:line,如果一次没救的跑偏还会哗哗刷两分钟废话,再加一个 -halt-on-error。然后只读第一条以 ! 开头的行,它下面全部忽略。第一个真错之后 TeX 一直在自救,而正是这些自救动作成串地吐出 Missing } inserted 和 Runaway argument?,让一个长文件看上去像塌了方。修掉最上面那一条再重编,比读四屏日志划算得多。

    接着让 TeX 把过程露出来。\errorcontextlines 控制一条错误下面能看见多少上下文,而 LaTeX 内核把它初始化成 -1,也就是什么都不给。导言区写一句 \setcounter{errorcontextlines}{20}——它是个计数器,是那条原语的别名,所以寻常接口照用——TeX 就会把正在读的那些行以及自己所在的展开层级一并打出来。往往就是这一行,决定你手里是一条报在第 1 行的 Undefined control sequence,还是知道了究竟哪个宏包的哪个宏展开出了它。

    然后对半砍,一步只接受一次构建。如果这本书每章一个 \include,那把尺子就是 \includeonly{ch07},它在缩小搜索范围的同时还让编号与交叉引用保持一致。如果是一个四千行的单文件,就机械地切——sed -n '1,1200p' main.tex > half.tex,补一个 \end{document},编——然后仍然失败的那一半留下。如果失败闻起来像宏包,就改为对导言区做对半,只留任何文档类都必需的东西。二十二章变成五次构建;四千行变成一个仍然报错的九行文件,而九行的失败通常不必任何工具就能看出来。这就是 k >= log2(n) 用在一篇文档上的含义。

    除了删,还有一条路是噤声:TeX 层面用 \iffalse...\fi,LaTeX 层面用 \excludecomment{env},后者更结实,因为它的结束标记是按逐字方式扫的,里面的花括号不配对或有 verbatim 内容都伤不到它。有两种情形二分是用错了工具,而且都很常见。文档编得出来但结果不对,请倒过来从 PDF 往回推:一个 ?? 是少跑了一遍或标签不在作用域里,凭空少一列是个没转义的 &,一章开在左页那是 openright 而不是 bug。至于只在某台机器上才出现的失败,直接跳到最后一节,因为差异不在你的源码里。

    \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
    对半砍的阶梯:每种形状的文档各自该用哪件工具,以及凭日志里的哪几族文字决定该留下哪一半。

    哪个宏包、哪个文件、哪些字节:版本漂移与可复现构建

    只在一台机器上重现、另一台上偏不重现的 bug,出于版本差异的概率远比人们假设的高,而日志一次就能定案。把 \listfiles 放在导言区最前面,LaTeX 会在日志末尾写出它用到的每一个文件及其版本与日期;两份这样的日志互相对 diff,作祟者通常就是唯一不同的那一行。kpsewhich --all package.sty 列出这台机器上所有副本并告诉你是哪一个在生效,你家目录里那棵过时的树就是这么被揪出来的。至于 -recorder 生成的 .fls,它是引擎实际读过的路径清单,能回答「正在被 input 的那个文件,是不是你以为自己正在改的那个」。

    PDF 默认并不字节稳定:它把生成时刻记进 /CreationDate 和 /ModDate,又从这两个值导出一个文件标识符,所以源码一字未改,两次构建的 trailer 也不相同。pdfTeX、XeTeX、LuaTeX 三个都认环境变量 SOURCE_DATE_EPOCH,也就是自 Unix 纪元起的秒数,会用它们代替系统时钟来填那几个日期和那个标识符;2019 年之前的 TeX Live 还额外要求 FORCE_SOURCE_DATE=1,在较新的安装上照设也无害。导出一个固定值——通常取提交日期——然后 sha256sum thesis.pdf 两次给出的就是同一个答案。

    这不是吹毛求疵而是地基。输出逐字节稳定,你才能按哈希去缓存一次构建,才能证明重新生成的 PDF 确实是因为你以为的那个原因而不同,才能归档一份「字节仍有意义」的提交。还有两处漂移出于同一理由必须钉住:\today 以及任何 \date{\today} 都把墙钟日期烤进了正文,凡指望重编的东西就该写一个明确的日期;以及自带时间戳的生成图——页脚印着日期的那种曲线图——会把整个问题原封不动搬到上一层去。

    CI 那边剩下的事就是别让地板移动。TeX Live 的安装按发行年份加一份宏包清单的哈希来缓存,而不是每次构建重装;镜像或安装器 URL 钉在某一个发行版上,今天绿的构建下个月才可能还是绿的;一条号称可复现的流水线里绝对不要跑 tlmgr update --all。引擎也要和发行版一起钉住:.latexmkrc 里写死 $pdf_mode,或者在作业步骤里明确写 latexmk -pdfxe thesis.tex,源码里再用 \RequireTUTeX 或 \RequirePDFTeX 负责在两者不一致时抱怨一声。构建命令里加个 -time,每次 CI 运行的日志就白送你一份属于自己文档的性能记录。

    耗时这本账上最后一笔恰恰最容易被忘:view 和 print 也是规则,所以无人值守的作业请显式要 $view = 'none'。还有 hyperref 要最后加载——不是因为它快,而是由于一个链接目标在这一遍写下、下一遍才被读到,这本身就是一条要求重跑的信号——与题注里那个 \pageref 让构建迟迟安定不下来是同一个道理。一个永远不收敛的慢构建,是一个穿着性能外衣的正确性 bug。

    \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})
    上面那个等式只有在时间戳被钉住之后才成立。同一份源码在不同时刻的两次构建,是同一份文档、却是不同的字节;让这两句话不再互相矛盾的就是 SOURCE_DATE_EPOCH。
    % 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}

    本课速查

    每节抽一行关键代码:点小节名跳到对应位置,代码一键复制。

    小节 关键代码
    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

    常见错误

    • 还没量就先优化。时间其实被一张六百行的表吃掉时,给错的那几章套上 \includeonly 毫无效果;只有 latexmk -time 会告诉你哪根杠杆上真压着东西。
    • 去读日志里最后一条错误。TeX 报的是第一条,此后的恢复动作一塌糊涂,所以能修的只有头那一行 !;在那行消失之前,它下面全是噪声。
    • 把 [draft] 或 [demo] 状态的成品交了出去。demo 从不打开文件,于是写错的路径隐了形,你量出来的分页也不是真的。快速构建要用 draftwatermark 盖个戳,开关则放进标记文件而不是放进源码。
    • 深夜草拟时写下的 samples=1000 忘了改回来。那是默认量的四十倍,按每条曲线、每一遍都要付。用 \tikzexternalize 把图缓存下来,或者在草拟阶段就把这个数字降回去。
    • 坐等 \timing 或 \usepackage{fast-draft} 存在。TeX Live 里两样都没发货:前者不是一条 TeX 命令,后者压根没有同名宏包。该用的是 shell 的 time 命令、latexmk -time,以及在 \pdfelapsedtime、\XeTeXelapsedtime 或 os.clock() 外面包四行。
    • 靠删 .aux 来修一个引用。你扔掉的是全部已经解析好的标签与引文,下一次构建因此要走完整个遍数循环;而如果还残留着一条 \includeonly,各章编号就会对着一份过时的辅助文件去排。
    • 把没完没了的 Label(s) may have changed 归咎于工具。真相是文档里有东西在改动它自己所在的那一页——题注里指向本页的 \pageref,或者某个每遍都重写内容的宏包。先把元凶找出来,再去动 $max_repeat。
    • 照博客的说法给 XeLaTeX 写 $pdf_mode = 4。在 latexmk 里 4 是 LuaLaTeX、5 才是 XeLaTeX;写错通常也照样编得过,代价就藏在这里,很难被察觉。
    • 在一篇论文里直接用 \tracingall。它是一整把计数器的打包,其中包括 \errorcontextlines=\maxdimen,输出量大得离谱;它该用在你二分出来的那个九行文件上,用完以 \tracingnone 关掉。
    • 按哈希做缓存的 CI 项目里还留着 \today 和没钉住的时间戳。于是每次运行都不一样、缓存永远不命中,而 SOURCE_DATE_EPOCH 只能修好 PDF 头部,修不了正文里的那个日期。

    关于本课的常见问题

    我的 LaTeX 怎么编得这么慢?
    几乎总是四者之一:曲线和 TikZ 图每遍都重算、表格太大、遍数多于文档实际需要、或者某个宏包为了凑某件事在反复迭代(tabularx、longtable、siunitx 的 S 列、microtype)。别猜,先确定是哪一种:latexmk -time 会按规则打印秒数,对日志数一遍「Output written」出现几回,而 \includeonly 或一份用 sed 截出来的复印件则告诉你代价是不是被单个文件独占。之后该外置图就外置、该把表格当生成文件提交就提交、草拟期间把采样点数降下来,遍数的事交给 latexmk 去管。
    graphicx 的 draft 和 demo 差在哪里?
    两者都拿盒子换掉图片,也都会被文档类选项 draft 隐含带上、被 final 覆盖回去。分别在于:draft 画一个含文件名的方框,但仍然会打开文件去量它,所以尺寸依旧可信;demo 直接还你一个定尺寸的盒子,磁盘根本不碰,这更快也更危险——路径写错不再是错误,版面也不再是将要印出来的那一版。逐图控制只需在引入图片那条命令的方括号选项里补上 draft;把待办宏包也带上同一个选项加载,就是同一思路用在页边注而不是图片上。
    一篇编不过的 LaTeX 文档该怎么查?
    先把失败弄得又便宜又清楚,再对输入做对半砍。让引擎跑在非停止模式、并让每条消息都带上文件名和行号,然后只看第一条以 ! 开头的行,它下面那串连锁反应全部不理。把 errorcontextlines 这个计数器调到 20 才看得见读取上下文与展开层级,因为内核默认的 -1 两样都不给。然后二分:书若按章拆开就用 \includeonly 只编那一章,单文件就用 sed 取行号区间,怀疑宏包就把导言区对半分;想让一整块噤声又不至于删掉,用 \excludecomment 或 \iffalse...\fi。缩到九行的时候,病因通常已经肉眼可见;途中要确认某个名字此刻归谁定义,用 \show 问一句。
    latexmk 究竟替我做了哪些手工做不到的事?
    三件。第一件是记账,每次运行读了什么、写了什么都被留下——凭引擎那个记录文件清单的选项(默认就开着,产出一份 .fls 清单),再加一份存有大小、时间与哈希的 .fdb_latexmk,因此没动过的文档压根不会被重编。第二件是决定该跑哪些规则,辅助文件开口要 biber 或 bibtex 时它就去跑一遍。第三件是不停重跑引擎,直到日志不再要求为交叉引用再来一遍,而重跑次数有个上限。这三件你都能手工做,那是很好的学习方式、却很糟的工作方式;再加一个 -time,你顺便还拿到每条规则各花了几秒。
    怎么让 LaTeX 构建变得可复现?
    把时钟钉住,把工具链也钉住。导出一个常数 SOURCE_DATE_EPOCH,让 PDF 里那几个日期和文件标识符不再漂(2019 以前的 TeX Live 再加一个 FORCE_SOURCE_DATE=1);用写明的 \date{} 替掉 \today;字体与生成的图随项目一起发出去,别让任何东西依赖某台具体的机器。在 CI 里选定投哪个 TeX Live 发行版而不是随手升级,并在 .latexmkrc 里把引擎写死。检验它成没成只需一个动作:同一份源码编两次,两个 sha256sum 是否一模一样。
    想看清一个宏展开成什么、或一页上装了什么,该用什么?
    看展开,就用 \tracingmacros=1 起头、\tracingmacros=0 收尾把那段围起来:TeX 会把它展开的每个宏连同代入实参后的样子一并记进日志,#1 到底收到了什么就是这么看见的。看装配好的成品则用 \showoutput——它打开的是 \tracingoutput,并把盒子的深度与宽度都调到 maxdimen,于是每页已输出的盒结构被整个 dump 出来;注意它同时切到了 errorstopmode,别长期留着。\tracingstats 报内存与页面用量,\show\foo 打一条定义就停下来,\listfiles 把用到的每个文件及其版本记在日志末尾。至于 \tracingall,那是把所有开关一次全打开,只适合配一个最小文件。

    实时演示:直接编辑 LaTeX,立刻看渲染结果

    预览随输入实时更新——不妨故意写坏一次,看看报错长什么样。

    KaTeX 错误
    试一个例子

    继续读

    同一个东西的三个入口:记法本身、讲它的那一课、以及真正用它写东西的一篇文章。