Last active
November 9, 2018 16:11
-
-
Save vmagamedov/3e4d7304ab6194584be4733d5660a64f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
01e8e2aa-cd8c-c37e-4689-5db093f8847f | |
01e8e2aa-cd8c-c6bc-4689-5db093f88480 | |
01e8e2aa-cd8c-c842-4689-5db093f88481 | |
01e8e2aa-cd8c-c98c-4689-5db093f88482 | |
01e8e2aa-cd8c-cb30-4689-5db093f88483 | |
gen_uuid() -> 0.047747763 | |
uuid.uuid1() -> 0.06972335500000001 | |
uuid.uuid4() -> 0.10280339599999999 | |
ObjectId() -> 0.05833711899999999 | |
uuid0.generate() -> 0.12896245299999998 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import uuid | |
import time | |
import struct | |
import threading | |
_local = threading.local() | |
def gen_uuid(): | |
"""Generates time-ordered UUIDs | |
Contains: | |
- 8 bytes - count of 100ns intervals since 1582-10-15 | |
- 4 bytes - randomly generated once per thread | |
- 4 bytes - cyclic counter which starts from random number | |
""" | |
try: | |
_local.thread_id | |
except AttributeError: | |
_local.thread_id = struct.unpack('>I', os.urandom(4))[0] | |
_local.counter = struct.unpack('>I', os.urandom(4))[0] | |
# 0x01b21dd213814000 is the number of 100-ns intervals between the | |
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00 | |
epoch = 0x01b21dd213814000 | |
now = int(time.time() * 10000000) | |
_local.counter = (_local.counter + 1) % 0xFFFFFFFF | |
return uuid.UUID(int=(((now + epoch) << 64) | |
+ (_local.thread_id << 32) | |
+ _local.counter)) | |
if __name__ == '__main__': | |
for _ in range(5): | |
print(gen_uuid()) | |
import timeit | |
import uuid0 | |
from bson.objectid import ObjectId | |
for code in [ | |
'gen_uuid()', | |
'uuid.uuid1()', | |
'uuid.uuid4()', | |
'ObjectId()', | |
'uuid0.generate()', | |
]: | |
print('{} ->'.format(code), | |
timeit.timeit(code, number=10000, globals=globals())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment