Skip to content

Commit 8d5a3af

Browse files
authored
Improve GridQubit dictionary lookup performance 3x (#3375)
According to the following profiling code, this change decreases the dictionary lookup time from 2100ns to 600ns on my machine. ``` import time import cirq d = {q: 5 for q in cirq.GridQubit.rect(3, 3)} q = cirq.GridQubit(0, 0) total = 0 t0 = time.monotonic() n = 100000 for _ in range(n): total += d[q] t1 = time.monotonic() print(total) print((t1 - t0) / n * 10**9, "nanoseconds per hash") ```
1 parent 8802685 commit 8d5a3af

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

cirq/devices/grid_qubit.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,26 @@ class GridQubit(_BaseGridQid):
275275
cirq.GridQubit(5, 4)
276276
"""
277277

278+
def __init__(self, row: int, col: int):
279+
super().__init__(row, col)
280+
self._hash = super().__hash__()
281+
282+
def __hash__(self):
283+
# Explicitly cached for performance (vs delegating to Qid).
284+
return self._hash
285+
286+
def __eq__(self, other):
287+
# Explicitly implemented for performance (vs delegating to Qid).
288+
if isinstance(other, GridQubit):
289+
return self.row == other.row and self.col == other.col
290+
return NotImplemented
291+
292+
def __ne__(self, other):
293+
# Explicitly implemented for performance (vs delegating to Qid).
294+
if isinstance(other, GridQubit):
295+
return self.row != other.row or self.col != other.col
296+
return NotImplemented
297+
278298
@property
279299
def dimension(self) -> int:
280300
return 2

0 commit comments

Comments
 (0)