Skip to content

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