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

Using bytes.hex instead of binascii.hexlify #104

Merged
merged 2 commits into from
Jun 10, 2022
Merged

Conversation

mapio
Copy link
Contributor

@mapio mapio commented Jun 8, 2022

To convert from bytes to an hex string the bytes.hex method is much faster than str(hexlify(…).decode('uft-8')).

Consider this rough test:

$ python3 -m timeit "b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o'.hex()"
5000000 loops, best of 5: 72.3 nsec per loop
$ python3 -m timeit -s "from binascii import hexlify" "hexlify(b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o').decode('utf-8')"
2000000 loops, best of 5: 137 nsec per loop
$ python3 -m timeit -s "from binascii import hexlify" "str(hexlify(b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o').decode('utf-8'))"
2000000 loops, best of 5: 194 nsec per loop

The documentation also reports that bytes.hex is a convenient way of doing what you need.

To convert from bytes to an hex string the `bytes.hex` method is much faster than  `str(hexlify(…).decode('uft-8'))`.

    $ python3 -m timeit "b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o'.hex()"
    5000000 loops, best of 5: 72.3 nsec per loop
    $ python3 -m timeit -s "from binascii import hexlify" "hexlify(b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o').decode('utf-8')"
    2000000 loops, best of 5: 137 nsec per loop
    $ python3 -m timeit -s "from binascii import hexlify" "str(hexlify(b'\x00\x00\x00\x00\x00\x19\xd6h\x9c\x08Z\xe1e\x83\x1e\x93O\xf7c\xaeF\xa2\xa6\xc1r\xb3\xf1\xb6\n\x8c\xe2o').decode('utf-8'))"
              2000000 loops, best of 5: 194 nsec per loop
@alecalve
Copy link
Owner

alecalve commented Jun 9, 2022

Nice, you can also remove the import since it's not used anymore

@mapio
Copy link
Contributor Author

mapio commented Jun 9, 2022

Sorry, I missed it. Now it is done.

@alecalve alecalve merged commit c06f420 into alecalve:master Jun 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants