← Back to section · Tutorials & Labs

Benchmarking Your Own PQC Code: Measuring Right Matters More Than Measuring Fast

A wrong benchmark is worse than none at all. This tutorial covers PQC benchmarking methodology: timing the three operations separately, warm-up and medians, separating binding overhead from algorithm cost, and liboqs's bundled speed_kem and speed_sig tools.

Published 22 November 2026 · 5 min read · PQ Frontier

Benchmarking Your Own PQC Code: Measuring Right Matters More Than Measuring Fast
AI-generated site artwork
Video explainer · PQC programming: calling real libraries

Here is a counterintuitive fact about benchmarking post-quantum code: a wrong benchmark is worse than no benchmark. With no numbers you at least know that you do not know; with wrong numbers you make algorithm choices based on precise-looking fiction. This tutorial is about methodology: how to time each KEM and signature operation separately, how to handle warm-up, jitter and statistics, and how to distinguish “the speed of the algorithm” from “the speed of your call stack” — both are useful numbers, but they must never be confused.

Rule one: time the three operations separately

Key generation, encapsulation and decapsulation are three operations with entirely different cost profiles. In ML-KEM, decapsulation performs a full decryption plus a re-encryption comparison (a requirement of the FO transform), making it noticeably more expensive than encapsulation; key generation, with its matrix expansion and sampling, has yet another profile. Signatures are similar: ML-DSA signing has variable duration because of rejection sampling, while verification is a deterministic fast path. Running all three in one loop and reporting a single average is weighing apples, oranges and the scale itself.

The correct structure times and reports each operation independently. Report the input and output sizes alongside (from details, or the C-side length_ fields), because speed without sizes is meaningless — ML-DSA-87 verification is slower than ML-DSA-44 partly because it processes more bytes.

Rule two: the timed region contains the operation and nothing else

The second most common error is drawing the timing boundary wrong. The Python skeleton below shows the correct shape — warm-up rounds excluded from the statistics, allocation kept outside the timed region where practical, and only the pure operation measured:

import oqs
import statistics
import time

ALG = "ML-KEM-768"
ROUNDS = 200

def bench(fn, rounds=ROUNDS):
    """Time fn over rounds iterations; return the median nanoseconds per call."""
    samples = []
    for _ in range(rounds):
        start = time.perf_counter_ns()
        fn()
        samples.append(time.perf_counter_ns() - start)
    return statistics.median(samples)

with oqs.KeyEncapsulation(ALG) as kem:
    public_key = kem.generate_keypair()

    # Warm-up: let caches and frequency scaling settle; these rounds don't count
    for _ in range(20):
        ct, _ = kem.encap_secret(public_key)
    enc_ns = bench(lambda: kem.encap_secret(public_key))

    ciphertext, _ = kem.encap_secret(public_key)
    dec_ns = bench(lambda: kem.decap_secret(ciphertext))

print(f"encaps median: {enc_ns / 1e6:.3f} ms")
print(f"decaps median: {dec_ns / 1e6:.3f} ms")

Key points. First, use a monotonic clock (time.perf_counter_ns), never a wall clock that system time adjustments can move. Second, report the median rather than the mean: OS scheduling, garbage collection and CPU frequency drops all create long-tail outliers, and the median is robust to them; a serious report adds the interquartile range as well. Third, run enough rounds: post-quantum operations take microseconds to milliseconds on a modern CPU, so 200 rounds is a floor — resolving a few percent of difference takes thousands. Fourth, write the environment into the report: CPU model, power state, Python and liboqs versions, parameter set. Without those, the numbers can neither be reproduced nor compared.

Rule three: separate algorithm cost from call-stack cost

A number measured in Python is the sum of algorithm, binding layer and interpreter. To learn how fast the algorithm itself is, use liboqs’s bundled C-level benchmark programs: the build tree contains speed_kem and speed_sig, which use the liboqs test framework’s timing harness to repeat each operation at high frequency and report operations per second and cycle counts:

# Run inside the liboqs build tree; prints ops/s and cycles per operation
./tests/speed_kem ML-KEM-768
./tests/speed_sig ML-DSA-65

Both yardsticks have their place: C-level numbers suit algorithm selection and cross-implementation comparison; Python-level numbers estimate your application’s real latency. A report must state which layer it used — comparing your Python numbers against the C numbers in a paper is the most common yardstick accident in benchmark reports. Also note that build options move C-level results substantially: whether native instruction optimizations for the target CPU are enabled can change results severalfold on the same machine, so the build configuration belongs in the report too.

Cycles versus wall time: choosing between two timing yardsticks

C-level benchmarks often report two numbers side by side: operations per second (from wall-clock time) and cycles per operation (from the CPU cycle counter). When they disagree, which should you trust? Modern CPU frequencies are dynamic: turbo boost, power management and thermal throttling all let the clock drift during a test run. The cycle counter measures how many clock cycles an operation consumed, which is naturally immune to frequency drift, so cycles are the more trustworthy figure for comparing the intrinsic cost of algorithms across runs; wall time measures what a user actually waits, which is the answer capacity planning needs. In practice, report both, and note the frequency conditions during the run: on a frequency-locked machine the two should agree, and a disagreement is itself a finding worth writing into the report. On laptops and cloud instances, where frequency is outside your control, the relative ordering by cycles is usually stable while absolute wall times can drift across an entire batch — state the environment type in the report so later readers know how to interpret your numbers.

Common mistakes checklist

  1. Recording the number from a single run. The first run includes cold caches and frequency ramp-up; it is the least representative sample of all.
  2. Timing prints, serialization or network round-trips. Then you measured your I/O, not the algorithm.
  3. Reporting means for long-tailed distributions. A handful of outliers drags the mean around; the median is the robust central estimate.
  4. Comparing numbers across machines or build configurations. Different CPU, compiler options or binding layer — the numbers are not comparable; re-measure on one machine with one configuration.
  5. Measuring speed but not size. The other half of post-quantum selection is bytes: public-key, ciphertext and signature sizes usually affect a protocol more directly than speed does. Report both sets of numbers together.

Summary

PQC benchmarking methodology compresses into three sentences: measure each operation separately, keep the timed region pure, and state the yardstick and environment in the report. Do those three things and your numbers will survive reproduction by others — and your own scepticism three months later. As a follow-up exercise, benchmark all three ML-KEM parameter sets with the same method and tabulate speed next to size, so you can see for yourself where each step up in security level spends its cost.

Tags: liboqsBenchmarkingPerformanceProgramming