Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 93c4e88

Browse files
committed
Improve message_id generation speed.
Messages ids are currently UUID4, and can't be yet replaced by a faster and more efficient format because of some backward compatibilities issues. The solution here is to generate an UUID4 as a base, and then replace its "time_low" part (4 bytes) by a randomly chosen unsigned integer (32bits) incrementing until a randomly chosen limit. When the limit is reached, a new UUID4 is generated and a new value is randomly chosen for the unsigned integer and its limit. Speedup is between ~4x and ~20x depending of the speed of the local entropy generation.
1 parent f1884db commit 93c4e88

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

zerorpc/context.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
import uuid
2727
import functools
28+
import random
2829

2930
import gevent_zmq as zmq
3031

@@ -42,15 +43,25 @@ def __init__(self):
4243
'get_task_context': [],
4344
'inspect_error': []
4445
}
46+
self._reset_msgid()
4547

4648
@staticmethod
4749
def get_instance():
4850
if Context._instance is None:
4951
Context._instance = Context()
5052
return Context._instance
5153

54+
def _reset_msgid(self):
55+
self._msg_id_base = str(uuid.uuid4())[8:]
56+
self._msg_id_counter = random.randrange(0, 2**32)
57+
self._msg_id_counter_stop = random.randrange(self._msg_id_counter, 2**32)
58+
5259
def new_msgid(self):
53-
return str(uuid.uuid4())
60+
if (self._msg_id_counter >= self._msg_id_counter_stop):
61+
self._reset_msgid()
62+
else:
63+
self._msg_id_counter = (self._msg_id_counter + 1) & 0xffffffff
64+
return '{0:08x}{1}'.format(self._msg_id_counter, self._msg_id_base)
5465

5566
def register_middleware(self, middleware_instance):
5667
registered_count = 0

0 commit comments

Comments
 (0)