Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of barrier() #11345

Merged
merged 7 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -3323,13 +3323,15 @@ def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet:
"""
from .barrier import Barrier

qubits = (
if qargs:
# This uses a `dict` not a `set` to guarantee a deterministic order to the arguments.
list({q: None for qarg in qargs for q in self.qbit_argument_conversion(qarg)})
if qargs
else self.qubits.copy()
)
return self.append(Barrier(len(qubits), label=label), qubits, [])
qubits = tuple({q: None for qarg in qargs for q in self.qbit_argument_conversion(qarg)})
return self.append(CircuitInstruction(Barrier(len(qubits), label=label), qubits, ()))
else:
qubits = self.qubits.copy()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The copy might not be necessary, but it does not hurt performance so I left it as it was originally coded.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine either way - self.qubits is a semi-dangerous object because it's a direct view onto QuantumCircuit internals and so mustn't be mutated, but the construction of a CircuitInstruction will consume it into a tuple anyway, so it wouldn't matter. Since it's irrelevant to performance, it's fine to just leave it.

return self._current_scope().append(
CircuitInstruction(Barrier(len(qubits), label=label), qubits, ())
)

def delay(
self,
Expand Down
11 changes: 11 additions & 0 deletions test/python/circuit/test_circuit_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,17 @@ def test_barrier(self):

self.assertEqual(qc, expected)

def test_barrier_in_context(self):
"""Test barrier statement in context, see gh-11345"""
qc = QuantumCircuit(2, 2)
qc.h(0)
with qc.if_test((qc.clbits[0], False)):
qc.h(0)
qc.barrier()

operation_names = [c.operation.name for c in qc]
self.assertNotIn("barrier", operation_names)

def test_measure_active(self):
"""Test measure_active
Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to
Expand Down