Most efficient way to generate random ID in Python?

Viewed 32

I have a project where I'm looking to generate millions of ID's. So any saved time would be beneficial.

I'm researching ways to get random ID's in Python in the most hyper-efficient way possible. I've been running scripts like below to measure different libraries.

print("random.randint() ", timeit.timeit(
    stmt="random.randint(0, 32)", setup="import random"))

print("uuid.uuid4() ", timeit.timeit(
    stmt="uuid.uuid4() ", setup="import uuid"))
print("uuid.uuid1() ", timeit.timeit(
    stmt="uuid.uuid1()", setup="import uuid"))

print("hashlib.md5() ", timeit.timeit(
    stmt="hashlib.md5()", setup="import hashlib"))
print("hashlib.md5() with seed ", timeit.timeit(
    stmt="hashlib.md5(b'99999999999')", setup="import hashlib"))

print("hashlib.sha256() ", timeit.timeit(
    stmt="hashlib.sha256()", setup="import hashlib"))

print("time.time() ", timeit.timeit(
    stmt="time.time()", setup="import time"))

With the following outcomes:

random.randint()  0.43830480001633987
uuid.uuid4()  2.275573799997801
uuid.uuid1()  2.527538399997866
hashlib.md5()  0.11704000001191162
hashlib.md5() with seed  0.12004000000888482
hashlib.sha256()  0.11938629997894168
time.time()  0.27248729998245835

Are there other ways to efficiently get a unique ID?

In my use case, I have the following parameters:

  • Security not important: If a user can reverse engineer the source of the random ID, that's not a big deal here.
  • Millisecond level collisions: Assigning ID's will happen quickly to the point where (depending on the machine), I suppose duplicates can be assigned.
  • Characters not important: ID can be made up of any characters.

What I've read so far:

0 Answers
Related