diff --git a/crates/circuit/src/circuit_data.rs b/crates/circuit/src/circuit_data.rs index 1aed43de0a21..da49f9edc605 100644 --- a/crates/circuit/src/circuit_data.rs +++ b/crates/circuit/src/circuit_data.rs @@ -31,6 +31,7 @@ use pyo3::types::{IntoPyDict, PyDict, PyList, PySet, PyTuple, PyType}; use pyo3::{import_exception, intern, PyTraverseError, PyVisit}; use hashbrown::{HashMap, HashSet}; +use indexmap::IndexMap; use smallvec::SmallVec; import_exception!(qiskit.circuit.exceptions, CircuitError); @@ -983,6 +984,22 @@ impl CircuitData { self.param_table.clear(); } + /// Counts the number of times each operation is used in the circuit. + /// + /// # Parameters + /// - `self` - A mutable reference to the CircuitData struct. + /// + /// # Returns + /// An IndexMap containing the operation names as keys and their respective counts as values. + pub fn count_ops(&self) -> IndexMap<&str, usize, ::ahash::RandomState> { + let mut ops_count: IndexMap<&str, usize, ::ahash::RandomState> = IndexMap::default(); + for instruction in &self.data { + *ops_count.entry(instruction.op.name()).or_insert(0) += 1; + } + ops_count.par_sort_by(|_k1, v1, _k2, v2| v2.cmp(v1)); + ops_count + } + // Marks this pyclass as NOT hashable. #[classattr] const __hash__: Option> = None; diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 487f1e28e382..ebc63511ca7b 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -3516,10 +3516,8 @@ def count_ops(self) -> "OrderedDict[Instruction, int]": Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ - count_ops: dict[Instruction, int] = {} - for instruction in self._data: - count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 - return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) + ops_dict = self._data.count_ops() + return OrderedDict(ops_dict) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). diff --git a/releasenotes/notes/port-countops-method-3ad362c20b13182c.yaml b/releasenotes/notes/port-countops-method-3ad362c20b13182c.yaml new file mode 100644 index 000000000000..93a92fa4c316 --- /dev/null +++ b/releasenotes/notes/port-countops-method-3ad362c20b13182c.yaml @@ -0,0 +1,5 @@ +--- +features_circuits: + - | + The :meth:`~.QuantumCircuit.count_ops` method in :class:`.QuantumCircuit` + has been re-written in Rust. It now runs between 3 and 9 times faster.