quantumlib / Cirq

A Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
Apache License 2.0
4.24k stars 1.01k forks source link

Cache Qid instances for common types #6371

Closed maffoo closed 9 months ago

maffoo commented 9 months ago

Here we add caches of common qubit types GridQubit, LineQubit, and NamedQubit (and their associated Qid types) so that we can reuse instances of these objects. Operations on these objects are extremely common, so reusing instances can have significant performance benefits, in particular because hashes do not need to be recomputed and equality comparisons can be short-circuited with instance equality in common cases.

codecov[bot] commented 9 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (6d437c4) 97.80% compared to head (88018d7) 97.81%.

:exclamation: Current head 88018d7 differs from pull request most recent head a181472. Consider uploading reports for the commit a181472 to get more accurate results

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #6371 +/- ## ======================================= Coverage 97.80% 97.81% ======================================= Files 1111 1111 Lines 96877 96948 +71 ======================================= + Hits 94754 94825 +71 Misses 2123 2123 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

mpharrigan commented 9 months ago
maffoo commented 9 months ago
  • Is there anything in the standard library for doing this automatically?

I don't know of anything to do this automatically. Which is unfortunate because it seems like a rather natural thing to do, and in fact I think we could improve performance by doing this for other heavily-used cirq classes as well.

  • should we limit the cache size? What If I make, run/simulate, and garbage-collect a whole lot of circuits on a whole lot of different qubits?

We could do that, though I suspect it's not common to create so many different qubits that this would matter.

maffoo commented 9 months ago

Changed to use a WeakValueDictionary for caching.