Skip to content

Commit e8cd84d

Browse files
authored
Cache lexicographical topological sort key in DAGNode (Qiskit#4040)
This commit caches the string sort key used for lexicographical topological sort as an attribute in DAGNode objects. Currently when retworkx's lexicographical topological sort call is called it needs to call the python callable provided to get a string used for sorting. Prior to this commit about 70% of the cumulative time spent in the lexicographical topological sort function is spent in python. This is because everytime it is sorting a new DAGNode it has to call str(x.qargs) which spends all that time constructing the string including a dict.get() and bit and register repr() calls, etc. To avoid this unecessary overhead at run time this commit adds a sort_key attribute to the DAGNode class which is set during __init__() and updates to the qargs property. Then the DAGCircuit lexicographical topological sort wrapper method changes the callable to use this attribute. Doing this eliminates all the overhead from calling back to python because it simply becomes attribute access.
1 parent f4c5156 commit e8cd84d

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

qiskit/dagcircuit/dagnode.py

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def __init__(self, data_dict, nid=-1):
3030
"""Create a node """
3131
self._node_id = nid
3232
self.data_dict = data_dict
33+
self.sort_key = str(self.qargs)
3334

3435
@property
3536
def type(self):
@@ -64,6 +65,7 @@ def qargs(self):
6465
def qargs(self, new_qargs):
6566
"""Sets the qargs to be the given list of qargs."""
6667
self.data_dict['qargs'] = new_qargs
68+
self.sort_key = str(new_qargs)
6769

6870
@property
6971
def cargs(self):

qiskit/dagcircuit/retworkx_dagcircuit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def topological_nodes(self):
107107
generator(DAGNode): node in topological order
108108
"""
109109
def _key(x):
110-
return str(x.qargs)
110+
return x.sort_key
111111

112112
return iter(rx.lexicographical_topological_sort(
113113
self._multi_graph,

0 commit comments

Comments
 (0)