Python generates a random: uuid v. Md5 v. Random which is most efficient or * ineffective *

I want to generate a random short sixth string (like 8 digits or 16 bit).

There are many options, for example from the top of the head:

uuid.uuid4().hex[:8]
md5().hexdigest()[:8]
"{0:08x}".format(int(random.random()*1000000000))[:8]

      

What I'm wondering is if there is some reason why any of these methods would be more effective than any others, or vice versa, if someone was particularly evil, ineffective ?

Anyone have any good oil?

Any suggestions for the cheapest way to accomplish this operation in python?

+3


source to share


2 answers


Try:

> %timeit uuid.uuid4().hex[:8]
100000 loops, best of 3: 7.46 µs per loop

> %timeit "{0:08x}".format(random.randint(0, 0xffffffff))
100000 loops, best of 3: 2.05 µs per loop

> %timeit binascii.hexlify(os.urandom(4))
1000000 loops, best of 3: 1.74 µs per loop

      

It is notable here that the bits from are random

not suitable for cryptographic purposes, so while this is most likely the fastest, it still may not be what you want.



If you're looking for insanely efficient, just get a whole bunch of random data ahead of time :)

> randomdata = binascii.hexlify(os.urandom(1024))
> %timeit randomdata[64:72]
10000000 loops, best of 3: 101 ns per loop

      

+5


source


Your best bet is to ask what exactly you want: 4 random bytes converted to hex. This ensures that you get the same amount of entropy as you ask for.

>>> binascii.hexlify(os.urandom(4))
'da20d2bd'
>>> binascii.hexlify(os.urandom(4))
'3266db8e'
>>> binascii.hexlify(os.urandom(4))
'4eb079dd'
>>> binascii.hexlify(os.urandom(4))
'46e3265e'

      



urandom

Returns cryptographically secure random data as a bonus .

+4


source







All Articles