Skip to content

Commit

Permalink
Fix quadratic dependency in QuantumCircuit.add_bits (Qiskit#11546)
Browse files Browse the repository at this point in the history
This is in the Python space component only.  When `add_bits` is called
many times, it constructs as temporary set of the union of all qubits
and clbits present in the circuit in order to calculate an intersection
with the input.  This causes the method to be linear in the number of
bits already present in the circuit, whereas it should be amortised
linear in the _to be added_.

This commit fixes the intersection to be a manual calculation that does
not construct three temporary set objects, removing the quadratic cost.
  • Loading branch information
jakelishman authored and ShellyGarion committed Jan 18, 2024
1 parent 8b84273 commit b7cdd28
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1955,7 +1955,9 @@ def add_register(self, *regs: Register | int | Sequence[Bit]) -> None:

def add_bits(self, bits: Iterable[Bit]) -> None:
"""Add Bits to the circuit."""
duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits)
duplicate_bits = {
bit for bit in bits if bit in self._qubit_indices or bit in self._clbit_indices
}
if duplicate_bits:
raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}")

Expand Down

0 comments on commit b7cdd28

Please sign in to comment.