Skip to content

Commit

Permalink
Improve GridQubit dictionary lookup performance 3x (quantumlib#3375)
Browse files Browse the repository at this point in the history
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")
```
  • Loading branch information
Strilanc authored Sep 30, 2020
1 parent 8802685 commit 8d5a3af
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions cirq/devices/grid_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,26 @@ class GridQubit(_BaseGridQid):
cirq.GridQubit(5, 4)
"""

def __init__(self, row: int, col: int):
super().__init__(row, col)
self._hash = super().__hash__()

def __hash__(self):
# Explicitly cached for performance (vs delegating to Qid).
return self._hash

def __eq__(self, other):
# Explicitly implemented for performance (vs delegating to Qid).
if isinstance(other, GridQubit):
return self.row == other.row and self.col == other.col
return NotImplemented

def __ne__(self, other):
# Explicitly implemented for performance (vs delegating to Qid).
if isinstance(other, GridQubit):
return self.row != other.row or self.col != other.col
return NotImplemented

@property
def dimension(self) -> int:
return 2
Expand Down

0 comments on commit 8d5a3af

Please sign in to comment.