Quantum circuit optimization is a trade-off, not a single switch. This guide shows how to reduce circuit depth, total gates, and especially two-qubit gates before execution, while checking that transpilation preserves the intended computation and does not introduce an unacceptable fidelity or runtime cost.
Overview
A circuit’s gate count is the total number of operations. Its depth is the number of sequential layers required when operations on different qubits can run in parallel. These metrics describe different costs: removing gates can reduce compilation and execution work, while reducing depth can limit the time during which qubits are exposed to noise.
Two-qubit gates deserve separate attention. They often require more hardware resources and can be more sensitive to calibration and connectivity constraints than single-qubit operations. A circuit with fewer total gates is not automatically better if its remaining two-qubit operations are arranged in long dependent chains or require costly routing.
The practical objective is therefore to minimize a useful cost vector rather than one number:
- total operation count;
- two-qubit operation count;
- critical-path depth;
- routing operations such as swaps;
- estimated execution time and shot cost; and
- observed accuracy on the target simulator or device.
Optimization should preserve the circuit’s observable behavior. Before changing it, define what must remain equivalent: a full state, a set of expectation values, a probability distribution, or a particular algorithmic success metric. For testing practices, see How to Test Quantum Circuits: Unit Tests, Assertions, and Regression Checks.
How to estimate
Start with a baseline circuit and record metrics before transpilation and after targeting a specific backend. At minimum, record qubit count, depth, total gates, two-qubit gates, measurements, and the transpiler or compiler settings. If the workflow uses repeated measurements, also record shots and the number of circuit variants. A shorter circuit is not necessarily cheaper if optimization requires many separately measured circuits.
1. Establish the baseline
Run the original circuit on an ideal simulator when possible. Save either the statevector, exact probabilities, or expectation values relevant to the application. Then run the same logical circuit through the target backend’s compiler and record the mapped result. This separates logical complexity from hardware-induced overhead.
2. Compare weighted costs
A simple planning score can make trade-offs visible:
weighted cost = a × depth + b × two-qubit gates + c × total gates + d × swaps
The coefficients are project assumptions, not universal constants. Set a larger weight for the metric that most affects your experiment. For a noisy device with limited connectivity, two-qubit gates and swaps may deserve more weight than single-qubit gates. For a simulator benchmark, depth and memory growth may matter more.
3. Use the compiler, then inspect it
In Qiskit, a typical first comparison uses the same circuit, backend, and seed while changing the optimization level. The exact available options can vary by installed version and backend, so verify them in the version’s documentation.
from qiskit import transpile
for level in range(4):
compiled = transpile(
circuit,
backend=backend,
optimization_level=level,
seed_transpiler=7
)
print(level, compiled.depth(), compiled.size())Do not treat the highest setting as automatically best. Compare the compiled circuit’s depth, two-qubit operations, routing overhead, compile time, and application-level results. A compiler may find a smaller circuit with a layout that performs poorly on a particular coupling map, while a different layout produces a deeper-looking circuit but fewer problematic interactions.
4. Validate equivalence
For small circuits, compare statevectors or amplitudes up to the expected global phase. For larger circuits, compare ideal probabilities, sampled distributions, or expectation values. On hardware, repeat the comparison with a fixed shot budget and confidence interval where practical. If the result changes, determine whether the cause is a logical rewrite, measurement ordering, transpilation, sampling variation, or device noise.
Inputs and assumptions
Before optimizing, create a short worksheet with these inputs:
- Logical circuit: qubit count, classical registers, measurements, parameter values, and circuit family.
- Target: simulator or device, native gate set, coupling map, supported instruction durations, and basis restrictions.
- Baseline metrics: depth, total gates, single-qubit gates, two-qubit gates, swaps, and measurement count.
- Quality metric: state fidelity, expectation-value error, distribution distance, success probability, or another application-specific measure.
- Execution assumptions: shot count, number of parameter points, batching strategy, queue or runtime limits, and whether compilation is repeated.
- Reproducibility: SDK version, compiler settings, layout settings, random seeds, and backend calibration snapshot when available.
Keep logical optimization separate from hardware mapping. Logical rewrites include removing adjacent inverse gates, combining rotations on the same axis, and commuting independent operations to expose cancellation. Mapping optimization chooses physical qubits and inserts routing operations. Mixing both steps without recording intermediate metrics makes it difficult to identify the source of an improvement or regression.
Useful manual transformations
Cancellation: Adjacent inverse operations such as a gate followed by its inverse can be removed. The same idea applies to repeated self-inverse gates when their product is the identity.
Rotation combination: Consecutive rotations about the same axis can often be combined by adding their angles. Check parameter conventions and measurement basis before applying this rewrite.
Commutation: Operations acting on separate qubits can be reordered. Some operations on shared qubits also commute, but this must be established from their definitions rather than assumed. Reordering can place inverse gates next to each other or shorten the critical path.
Template replacement: Replace a known gate sequence with an equivalent sequence that uses fewer native operations. Measure this after decomposition because an apparently compact abstract circuit may expand into more hardware-native gates.
Layout checks: Inspect whether frequently interacting logical qubits are placed on well-connected physical qubits. A poor initial layout can create several swaps and erase the benefit of logical simplification.
Worked examples
Example 1: cancellation and depth
Assume an illustrative four-qubit circuit begins with 42 operations, 10 two-qubit operations, and depth 24. Inspection finds three adjacent inverse pairs and two independent single-qubit rotations that can be combined. After these logical rewrites, the circuit has 35 operations, 10 two-qubit operations, and depth 20. The improvement is meaningful, but it has not reduced the most sensitive class of operations. The next step is to evaluate whether commuting operations can shorten two-qubit dependencies without changing the measured observable.
Example 2: mapping trade-off
Suppose the simplified circuit is transpiled for a backend with limited connectivity. One initial layout produces 35 operations, 16 two-qubit operations, 6 swaps, and depth 31. A second layout produces 39 operations, 12 two-qubit operations, 2 swaps, and depth 25. The second result has more total operations but fewer routing operations, fewer two-qubit operations, and lower depth. If the hardware is sensitive to two-qubit error and idle time, it may be the stronger candidate. Confirm that choice with the application’s output metric rather than gate counts alone.
Example 3: a repeatable comparison table
| Version | Depth | Total gates | Two-qubit gates | Swaps | Quality result |
|---|---|---|---|---|---|
| Logical baseline | 24 | 42 | 10 | 0 | Reference |
| Manual rewrite | 20 | 35 | 10 | 0 | Within tolerance |
| Layout A | 31 | 35 | 16 | 6 | Higher error |
| Layout B | 25 | 39 | 12 | 2 | Within tolerance |
The numbers above are a method example, not a hardware benchmark. Use your own circuit and repeat the comparison with the same parameter values, shots, and validation method. For real-device preparation and result review, use the quantum circuits real-hardware checklist. If the optimized circuit still produces noisy estimates, optimization can be combined with an appropriate error-mitigation workflow; see Quantum Error Mitigation Methods.
When to recalculate
Recalculate circuit performance whenever the target backend, native gate set, coupling map, SDK version, compiler version, or optimization settings change. A circuit that is efficient on one device may require additional routing on another. Likewise, a compiler update can alter decomposition and layout decisions, so preserve the previous metrics as a regression baseline rather than assuming the new output is better.
Revisit the worksheet when you change the algorithm, add measurements, increase the number of variational parameters, alter shot count, or move from simulation to hardware. Recheck after calibration conditions change if the experiment depends on current device behavior. For simulator selection and scaling assumptions, compare the options described in Quantum Simulator Comparison.
Use this practical sequence for each release:
- Save the logical circuit and its application-level reference result.
- Compile with fixed, documented settings for each target.
- Record depth, total gates, two-qubit gates, swaps, compile time, and execution assumptions.
- Validate the observable result against the reference within a stated tolerance.
- Run the best candidates with equal shots and compare runtime and quality.
- Keep the winning configuration together with the SDK, backend, and layout metadata.
Review the comparison quarterly or whenever a major SDK or hardware generation changes. The goal is not the smallest circuit in isolation; it is the smallest well-validated circuit that preserves the computation and performs acceptably under the conditions in which it will actually run.