Skip to content

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

Closed

Description

@NewUserHa

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)

Activity

  1. added
    performancePerformance or resource usage
    stdlibStandard Library Python modules in the Lib/ directory
    3.12only security fixes
    on Nov 10, 2022
  2. added a commit that references this issue on Nov 11, 2022
  3. hauntsaninja commented on Nov 29, 2022

    @hauntsaninja
    Contributor

    Thanks for improving this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.12only security fixesperformancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions