-
-
Save DavidBuchanan314/51bb8f6219ea8bb7a603e0ad19725f6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import timeit | |
import numpy as np | |
def xor_bytes(a: bytes, b: bytes) -> bytes: | |
assert(len(a) == len(b)) | |
return bytes(a ^ b for a, b in zip(a, b)) | |
def xor_bytes_simd(a: bytes, b: bytes) -> bytes: | |
assert(len(a) == len(b)) | |
return ( | |
int.from_bytes(a, "little") ^ int.from_bytes(b, "little") | |
).to_bytes(len(a), "little") | |
def xor_bytes_numpy(a: bytes, b: bytes) -> bytes: | |
return ( | |
np.frombuffer(a, dtype=np.uint8) ^ np.frombuffer(b, dtype=np.uint8) | |
).tobytes() | |
# first, lets check all impls really do the same thing: | |
a = os.urandom(16) | |
b = os.urandom(16) | |
assert(xor_bytes(a, b) == xor_bytes_simd(a, b)) | |
assert(xor_bytes(a, b) == xor_bytes_numpy(a, b)) | |
for n in [1, 4, 8, 16, 128, 1024]: | |
a = os.urandom(n) | |
b = os.urandom(n) | |
print() | |
print(f"naive, n={n}", timeit.timeit("xor_bytes(a, b)", globals=locals())) | |
print(f"simd, n={n}", timeit.timeit("xor_bytes_simd(a, b)", globals=locals())) | |
print(f"numpy, n={n}", timeit.timeit("xor_bytes_numpy(a, b)", globals=locals())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment