Generate ids with itertools.count
Avoids the critical section with threading.Lock in favor of itertools.count. `count` objects are threadsafe, and their critical section is implemented in C and provide better performance that Python level locking.
This commit is contained in:
@@ -3,32 +3,39 @@
|
||||
#
|
||||
# SPDX-License-Identifier: BSD 2-Clause License
|
||||
#
|
||||
import collections
|
||||
import itertools
|
||||
|
||||
from threading import Lock
|
||||
|
||||
_COUNTS = {}
|
||||
_COUNTS_MUTEX = Lock()
|
||||
|
||||
_ID = 0
|
||||
_ID_MUTEX = Lock()
|
||||
_COUNTS = collections.defaultdict(itertools.count)
|
||||
_ID = itertools.count()
|
||||
|
||||
|
||||
def obj_id() -> int:
|
||||
global _ID, _ID_MUTEX
|
||||
with _ID_MUTEX:
|
||||
_ID += 1
|
||||
return _ID
|
||||
"""
|
||||
Generate a unique id for an object.
|
||||
|
||||
>>> obj_id()
|
||||
0
|
||||
>>> obj_id()
|
||||
1
|
||||
>>> obj_id()
|
||||
2
|
||||
"""
|
||||
return next(_ID)
|
||||
|
||||
|
||||
def obj_count(obj) -> int:
|
||||
global _COUNTS, COUNTS_MUTEX
|
||||
name = obj.__class__.__name__
|
||||
with _COUNTS_MUTEX:
|
||||
if name not in _COUNTS:
|
||||
_COUNTS[name] = 0
|
||||
else:
|
||||
_COUNTS[name] += 1
|
||||
return _COUNTS[name]
|
||||
"""Generate a unique id for an object.
|
||||
|
||||
>>> obj_count(object())
|
||||
0
|
||||
>>> obj_count(object())
|
||||
1
|
||||
>>> new_type = type('NewType', (object,), {})
|
||||
>>> obj_count(new_type())
|
||||
0
|
||||
"""
|
||||
return next(_COUNTS[obj.__class__.__name__])
|
||||
|
||||
|
||||
def exp_smoothing(value: float, prev_value: float, factor: float) -> float:
|
||||
|
||||
Reference in New Issue
Block a user