Part 4: First benchmarks

<- Part 3: Building the benchmark harness Part 5: More benchmarks (Not yet published)
   

Now that we have a harness to systematically capture our results for later analysis, we can begin comparing the performance of an implementation of TeX’s data structures in the original, 1980’s C style, with that of an implementation in modern C++ style. It turns out that even casually-designed benchmarks can contribute useful results.

To summarize the discussion so far, TeX’s original Pascal code implemented all the data structures from scratch, using WEB macros to make accessing the data superficially similar to higher-level constructs. The original code did not even use the facilities already available in Pascal, such as records or dynamic memory, let alone concepts that were developed later such as objects and class hierarchies. While this choice was justifiable under the constraints of the early 1980s, it appears dated and obscure viewed through the expectations of contemporary programming style.

In Part 2, I reimplemented these basic data structures twice in C++, once in a style closely resembling the original Pascal, once using the modern features of C++ 23 to the fullest. Comparing the source code, I found the modern version superior: more readable, shorter, and more able to benefit from static type checking.

What about runtime performance, though? There are potential arguments for either version to be slower. The older style might not be well-matched to modern architectures, with their pipelining, prefetching, and deep memory hierarchy, while the newer style might introduce inefficiences by its multiple layers of abstraction. To answer this question, we need to actually benchmark the respective performance of the two implementations.

Potential benchmarking approaches

There are many ways we could benchmark these implementations. One approach would be to compare them as general data structures, storing a variety of data in them and testing a range of access patterns, such as random versus sequential access.

But the structures are tailored to the needs of TeX. The data types are not general but are the specific box types required for text layout and the access patterns are always sequential. A more appropriate comparison would call these implementations in the patterns typically required by TeX.

The most accurate way to simulate TeX’s patterns would be to instrument TeX itself as it formats one or more documents, recording every time it creates, accesses, and deletes an item from these structures. Then a benchmark would call each implementation in exactly the same sequence, comparing execution time.

Instrumenting TeX this way would be a big effort. Just building TeX, without any change, requires installing an expansive, idiosyncratic toolchain and running complex Makefiles. For this casual project that is far too much work.

A simpler, albeit less accurate, comparison can be made instead by calling the implementations in a pattern that mimics our expectations of how TeX works. Less definitive in outcome but easier to implement, this is the approach I chose.

A first set of simple benchmarks

TeX will use these data structures according to the following typical sequence:

  1. Create a list of boxes.
  2. Run sequentially through the list once or a handful of times.
  3. Delete the list.

TeX is unlikely to run through a list more than a small number of times and will never attempt random access, given that they are linked lists.

Side note: As described in Part 2, there are additional TeX data structures not implemented in my sample code. These structures, such as the string table or table of equivalents, will have very different access patterns, including random access.

Given these patterns, a good first attempt at benchmarking can take this form:

  1. Create a list comprising one box of every type, each initialized to a typical value.
  2. Traverse the list zero or more times.
  3. Delete the list.

We include traversing the list zero times because that tells us the cost of simply creating and deleting lists. We might expect the original implementation to be faster, given that it uses a simple bespoke dynamic memory pool tailored to TeX’s needs, while the modern approach uses the general-purpose allocator provided by the compiler’s runtime.

Varying the number of list traversals allows us to compare how well each implementation supports efficient list access. The original implementation uses a single function and array lookups, while the modern implementation uses overloaded virtual functions.

The benchmarks vary the traversal count by 0, 1, 10, 20, 40, 60, and 100 traversals.

Other considerations

Some items to keep in mind:

  1. The lists in these initial benchmarks are much smaller than the lists in a production run of TeX. Typically, it will be processing a list of boxes and tokens comprising an entire page. Note that the traversals parameter to the current benchmarks refers to the number of times the benchmark will traverse a single instance of a short list, not the length of the list to be traversed.

  2. As described in Part 3 the Catch2 benchmark code warms up the processor cache and lower levels of the memory hierarchy before the first timing run, so the results should reflect a consistently warm cache.

  3. In the modern implementation, traversals of lists of Node objects are performed by recursive calls to Node::traverse_node() (for example, this call in List::traverse_node()). This is fine for the short lists in these first benchmarks but would risk stack overflow when applied to lists of representative length from actual TeX runs. Future benchmarks should replace the recursion with a loop.

Results for unoptimized code

The timings for the original style compiled with -O0 follow a tight pattern:

Plot of points and regression for Original -O0

The points are tightly clustered and closely follow the line of the linear regression. The times required for combined creation / deletion of the short list, as well as the time for a single traversal, are clearly consistent.

The timings for the modern style compiled with -O0 follow a similar pattern:

Plot of points and regression for Modern -O0

These points seem to have a slightlight larger spread at the higher traversal counts than the original style but overall this code also seems highly consistent.

Comparing the scales of the Y axes shows that the modern code is substantially slower than the original; we shall compare these in more detail in the next section.

Results for all versions of the code

Plotting both versions of the code, compiled both with no optimization and highest optimization, reveals clear patterns. At this scale, the individual points are just texture along the regression lines, so I’ll only plot the lines:

Plot of four regression lines, original and modern at -O0 and -O3

The patterns:

  1. Going from unoptimized to highly-optimized makes a big difference for the original code and an even bigger difference for the modern code. The improvement for the original code will in part be due to the replacement of external function calls with inline code, as described in detail in Part 2. The source of the greater improvement in the modern code is less obvious, given its simpler source structure.

  2. Optimization reverses the relative ordering of the two approaches: For unoptimized versions, the original code is faster while for the optimized versions, the modern code is faster, at least for higher traversal counts.

  3. For low traversal counts, the plot provides no clear indication of which optimized version is faster. I’ll explore this in detail in the next section.

  4. As a practical matter, there’s not that much difference between the two versions when compiled with the highest optimization.

  5. As an initial assessment of the potential impact of system noise, I ran the unoptimized modern code, which is the slowest of all versions, while playing a YouTube video. There was no observable change in the timings.

List creation / deletion at -O3

When the traversal count is 0, the benchmarks estimate the time to create and delete the short list. This benchmark was run 20 times for each code style at highest optimization, producing 20 estimates of the mean with a nonparametric 95% confidence interval. Sorting each list in ascending order of means and plotting the means with their intervals shows a consistent pattern:

Plot of means and nonparametric 95% CIs for -O3

There’s no good way to tease out a significance test from such a plot, due to the obvious dependence of each estimate (separate estimates of the same process), the heteroscedascity (unequal variances), and the multiple comparisons implied by comparing sorted values.

We can, however derive a general conclusion that the modern code is about 50 ns slower to create and delete the list than the original code. The intercepts for the regression lines agree: 198 ns for original, 257 ns for modern. I’m surprised by this—and frankly a bit disappointed—but the estimates are consistent.

How many traversals does it take for modern to be faster?

Plotting the lower traversal counts for the optimized versions shows where their speeds cross:

Plot of optimized versions, from 0 to 20 traversals

The more efficient traversals of the modern version make it faster than the original for 5 or more traversals. I am also surprised by this result. Offhand, I don’t see why either version should be particularly faster at traversal.

Conclusions and future questions

For production code, the important comparison is for optimized code, compiled at ‑O3. With optimization, there really isn’t an appreciable difference between the versions. The original version is faster at creating and deleting the short list, while the modern version is faster at traversing the list. By the time we make 5 traversals, the modern version is consistently faster, though to repeat, neither improvement is likely to make a practical difference.

We can summarize the above succinctly: When it comes to data structures, don’t bet against Don Knuth.

These results are not definitive, of course. No benchmark ever can be. They suggest some followup questions:

  1. How would the two approaches compare on a longer list, more representative of the lists actually processed by Tex?
  2. How do the two list creation version compare alone? How about list deletion?
  3. What changes does the optimizer make to produce such dramatic changes in both versions, especially in the modern version?
  4. Can we improve the modern version’s performance by using C++ features that allow the programmer to replace the standard dynamic memory allocation runtime with bespoke alternatives tailored to this specific data structure? Two possibilities are overriding new and delete and polymorphic allocators.

I’ll explore these questions in future posts.

Original style:

Modern style:

Shell script for running benchmarks

Juptyer notebook for analysis

Raw data from benchmarks