Quantum algorithm benchmarking is most useful when every comparison uses the same problem instances, measurement rules, execution conditions, and reporting format. This guide presents a repeatable Python workflow for comparing circuit versions, algorithms, simulators, and hardware backends using accuracy, runtime, depth, gate count, shots, memory, cost, and noise sensitivity.
Overview
A benchmark should answer a defined engineering question, not produce an isolated number. You might want to know whether a new ansatz improves solution quality, whether a transpiler setting reduces circuit depth, whether a simulator scales acceptably, or whether hardware noise changes the ranking of two algorithms.
Start by writing the comparison as a small experiment specification:
- Task: the optimization, classification, sampling, or simulation problem being solved.
- Variants: the algorithms, circuit versions, transpiler configurations, or backends being compared.
- Inputs: fixed problem instances, qubit counts, parameter initializations, and random seeds.
- Measurements: the metrics and statistical summaries that will determine the result.
- Execution conditions: shot count, simulator method, noise model, compilation options, and hardware settings.
Do not compare an ideal statevector result with a noisy hardware result and call the difference an algorithmic improvement. Those are different execution regimes. A fair benchmark either holds the regime constant or labels the comparison explicitly as a separate experiment.
For background on measurement counts, probabilities, confidence intervals, and error bars, see Quantum Measurement Results in Python. Circuit structure can also be inspected with the techniques in Visualizing Quantum States in Python.
How to estimate
Use a benchmark record for each independent run, then aggregate records rather than overwriting them. A useful minimum schema is:
run_id, algorithm, instance_id, backend, mode, seed,
qubits, shots, accuracy, objective_value,
wall_time_s, execution_time_s, depth,
total_gates, two_qubit_gates, peak_memory_mb,
estimated_cost, noise_level, status
Several metrics need precise definitions:
- Accuracy: use a task-specific measure. For a known optimum, this might be the fraction of runs reaching the optimum. For a classifier, define whether accuracy comes from sampled labels or an expectation-value threshold.
- Objective value: record the raw value as well as a normalized value when instances have different scales. For minimization, lower is better; for maximization, higher is better.
- Wall-clock time: the elapsed time observed by the client, including queueing, compilation, network overhead, and result retrieval when applicable.
- Execution time: time attributed to circuit execution if the platform exposes it. Do not substitute it silently for wall-clock time.
- Depth and gate count: record both pre-transpilation and post-transpilation values when possible. Hardware-compatible operations can differ substantially from the original circuit.
- Shots: the number of samples used for a result. A higher shot count can reduce sampling uncertainty but may increase execution time or cost.
- Memory: report peak process memory for local simulation, and distinguish allocated memory from the platform limit if you track remote execution.
- Cost: calculate it from the current provider model, such as shots, tasks, execution duration, or subscription allocation. Store the pricing version or date instead of hard-coding an assumption without a label.
- Noise sensitivity: compare an ideal baseline with one or more stated noise conditions. Report the change in task metric, not merely a generic noise label.
For repeated runs, report the median and a spread such as the interquartile range when timing has outliers. For success rates, retain the number of successes and total trials so another reader can reconstruct the proportion. Fixed seeds improve reproducibility, but they should not be the only seed tested: a result that depends on one initialization is a fragile result.
A compact Python template can keep experiment collection separate from analysis:
from dataclasses import asdict, dataclass
import csv
import time
@dataclass
class Result:
algorithm: str
instance_id: str
backend: str
mode: str
seed: int
qubits: int
shots: int
accuracy: float | None
objective_value: float | None
wall_time_s: float
depth: int | None
total_gates: int | None
two_qubit_gates: int | None
estimated_cost: float | None
status: str
def benchmark(run_fn, metadata):
start = time.perf_counter()
output = run_fn()
elapsed = time.perf_counter() - start
return Result(
**metadata,
accuracy=output.get("accuracy"),
objective_value=output.get("objective_value"),
wall_time_s=elapsed,
depth=output.get("depth"),
total_gates=output.get("total_gates"),
two_qubit_gates=output.get("two_qubit_gates"),
estimated_cost=output.get("estimated_cost"),
status=output.get("status", "ok"),
)
# Write each result as one durable row.
with open("benchmark_results.csv", "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=asdict(result).keys())
if f.tell() == 0:
writer.writeheader()
writer.writerow(asdict(result))
The execution adapter represented by run_fn should be specific to your SDK and backend. Keep that adapter small so that changing from a local simulator to a cloud target does not change the reporting logic. If you are maintaining Qiskit code, review SDK and primitive changes before interpreting differences as performance results; the Qiskit 2.x migration guide is a useful companion.
Inputs and assumptions
The benchmark is only as reliable as its recorded inputs. Store the following alongside the results:
- SDK and package versions, Python version, and operating environment.
- Backend name, simulator method, coupling or connectivity assumptions, and target selection settings.
- Original qubit count and transpiled qubit count.
- Optimization level, routing method, basis gates, layout, and any custom compilation pass.
- Problem-instance identifier and a checksum or serialized copy of the input where practical.
- Random seeds for parameter initialization, circuit generation, sampling, and noise generation.
- Shot count, number of repetitions, warm-up policy, and whether failed jobs were retried.
- Noise model, mitigation method, calibration context, and whether results were post-processed.
Separate algorithm quality from infrastructure overhead. A local run may include Python setup and compilation in wall time; a remote run may include submission and queue delays. Both measurements can be useful, but they answer different questions. Use labels such as compile_time_s, queue_time_s, execution_time_s, and client_time_s when the platform exposes those values.
Cost estimates should be treated as inputs, not permanent facts. Define a formula in configuration, for example estimated_cost = billable_units * unit_rate, and record the units, currency, account assumptions, and date. If no reliable rate is available, store billable usage and leave cost as unknown rather than inventing a price.
Noise comparisons also require discipline. Use the same circuit family, problem instance, shots, and success definition across conditions. A mitigation technique may improve a task metric while increasing circuit executions or runtime; report both effects. The guide to Quantum Error Mitigation in Python covers the validation considerations behind this trade-off.
Worked examples
Example 1: Comparing two circuit versions
Suppose version A and version B solve the same three problem instances. Run each version with identical seeds and shot counts, first in an ideal simulator and then under the same noise model. Record pre- and post-transpilation depth, total gates, two-qubit gates, objective value, success rate, and wall time.
Interpret the table by question, not by a single winner. If B has a lower post-transpilation two-qubit count and similar ideal accuracy but loses more accuracy under noise, investigate its layout and gate choices. If B has better accuracy but requires twice as many shots, report the quality-versus-resource trade-off. If the difference appears only in wall time, check whether compilation or startup overhead explains it.
Example 2: Estimating repeated-run success
Assume an algorithm is run 20 times with different seeds. It reaches the target condition in 13 runs. The empirical success rate is 13 / 20 = 0.65, or 65 percent. Store both values, not just the percentage. Also store the objective value from every run, because a failed run may still be substantially better than another failure. Repeat the experiment with a larger seed set before making a strong claim about reliability.
Example 3: Comparing simulator and hardware use
Use separate rows for ideal simulation, noisy simulation, and hardware execution. A practical summary might show:
algorithm, mode, accuracy, depth, two_qubit_gates,
shots, wall_time_s, estimated_cost, notes
The summary should not merge unlike time measurements. Instead, explain that ideal simulation estimates algorithmic behavior, noisy simulation isolates a chosen noise assumption, and hardware execution includes the conditions of a real target. This makes the benchmark useful for selecting the next experiment rather than declaring an absolute ranking.
When to recalculate
Recalculate the benchmark when any input that can affect the decision changes. This includes a new SDK or compiler version, a changed transpilation setting, a different simulator method, a new backend or connectivity map, altered shot counts, a revised noise model, or a change in the provider's billing inputs. Re-run when the problem size, parameter initialization strategy, or success criterion changes as well.
For ongoing projects, keep a small regression suite in continuous integration for local simulators and run a scheduled hardware or cloud sample when appropriate. Store raw counts and circuit metadata, not only a dashboard's averages. A test pattern such as the one in Testing Quantum Circuits in Python can help separate correctness checks from performance measurements.
Before publishing or using a benchmark for a design decision, complete this checklist:
- Define the task metric and direction of improvement.
- Freeze instances, seeds, shots, and execution conditions.
- Record both original and transpiled circuit metrics.
- Separate compilation, queue, execution, and client time where possible.
- Report repetitions, uncertainty, failures, and retries.
- Label pricing, backend, noise, and SDK assumptions with dates or versions.
- Save raw results so the summary can be recalculated.
This workflow turns quantum algorithm benchmarking into a maintainable Python experiment rather than a one-time comparison. Revisit the inputs when tools, backends, rates, or benchmark goals change, and the results will remain interpretable as your quantum application evolves.