This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: uuid.uuid4() fast optimization
Type: performance Stage: resolved
Components: Library (Lib) Versions: Python 3.10
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, mosquito, rhettinger, serhiy.storchaka
Priority: normal Keywords: patch

Created on 2021-10-21 15:03 by mosquito, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
0001-Generating-uuid.uuid4-up-to-three-times-faster.patch mosquito, 2021-10-21 15:03 patch
Pull Requests
URL Status Linked Edit
PR 29125 mosquito, 2021-10-21 15:05
Messages (3)
msg404607 - (view) Author: Mosquito (mosquito) * Date: 2021-10-21 15:03
I does a small experiment, and found out that if you generate UUID4 with int instead of sequence of bytes, then the generation of UUID4 occurs up to three times faster.

.. code-block: python

    import random
    import uuid

    print("uuid.uuid4()")
    %timeit uuid.uuid4()
    # 5.49 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

    print("uuid.UUID(int=random.getrandbits(128), version=4)")
    %timeit uuid.UUID(int=random.getrandbits(128), version=4)
    # 2.58 µs ± 94.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


I have already made fixes to my fork on GH, tell me, will it be useful to someone else besides me?
msg404612 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-10-21 15:44
random.getrandbits() is cryptographically weaker than os.urandom().
msg404631 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2021-10-21 18:29
We use os.urandom() because it is backed by a cryptographicly secure random number generator. The random module uses a non-secure RNG. While RFC 4122 does not mandate a CSRPNG, application often rely on unpredictable UUIDs. Correctness and security is more important here than performance.

If you need a faster uuid4 implementation, then you can role your own with a couple of lines of code:

import random
from uuid import UUID

def uuid4_fast():
    return UUID(int=random.getrandbits(128), version=4)
History
Date User Action Args
2022-04-11 14:59:51adminsetgithub: 89719
2021-10-21 18:29:24christian.heimessetstatus: open -> closed

nosy: + christian.heimes
messages: + msg404631

resolution: rejected
stage: patch review -> resolved
2021-10-21 15:44:43serhiy.storchakasetnosy: + rhettinger, serhiy.storchaka
messages: + msg404612
2021-10-21 15:05:06mosquitosetstage: patch review
pull_requests: + pull_request27402
2021-10-21 15:03:58mosquitocreate