Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stdlib secrets.token_hex() speeded up 2x #99305

Closed
NewUserHa opened this issue Nov 9, 2022 · 1 comment
Closed

stdlib secrets.token_hex() speeded up 2x #99305

NewUserHa opened this issue Nov 9, 2022 · 1 comment
Labels
3.12 bugs and security fixes performance Performance or resource usage stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@NewUserHa
Copy link
Contributor

NewUserHa commented Nov 9, 2022

Feature or enhancement

CPython 3.11 is on average 25% faster than CPython 3.10

Therefore hope the python 3.12 stdlibs can get optimized as well, since maybe web could use secrets tokens a lot

Pitch

cpython/Lib/secrets.py

Lines 48 to 59 in 7c9c993

def token_hex(nbytes=None):
"""Return a random text string, in hexadecimal.
The string has *nbytes* random bytes, each byte converted to two
hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
default is used.
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
"""
return binascii.hexlify(token_bytes(nbytes)).decode('ascii')

import os
t = os.urandom(32)

# Before:
timeit binascii.hexlify(t).decode('ascii') # 215 ns ± 6.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

# After: 
timeit t.hex() # 91 ns ± 1.6 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
@NewUserHa NewUserHa added the type-feature A feature request or enhancement label Nov 9, 2022
@AlexWaygood AlexWaygood added performance Performance or resource usage stdlib Python modules in the Lib dir 3.12 bugs and security fixes labels Nov 10, 2022
gpshead pushed a commit that referenced this issue Nov 11, 2022
simple code modernization.

Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
@hauntsaninja
Copy link
Contributor

Thanks for improving this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.12 bugs and security fixes performance Performance or resource usage stdlib Python modules in the Lib dir type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

3 participants