Created
February 17, 2022 15:18
-
-
Save hehehwang/76c261d93967bd3a71b529e5dfc3112e to your computer and use it in GitHub Desktop.
tuple comare benchmark
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
from random import randint | |
from timeit import timeit | |
def concat_bitshift(a, b, c): | |
return a << 40 | b << 20 | c | |
def deconcat_bitshift(c): | |
mask = 0xFFFFF | |
return c >> 40, (c >> 20) & mask, c & mask | |
nums = [[randint(1, int(1e8)) for _ in range(3)] for _ in range(1000)] | |
tuples = [(i[0], i[1], i[2]) for i in nums] | |
bits = [concat_bitshift(i[0], i[1], i[2]) for i in nums] | |
# print(sorted(tuples)) | |
# print([deconcat_bitshift(n) for n in sorted(bits)]) | |
setup = "from __main__ import concat_bitshift, deconcat_bitshift, tuples, bits" | |
t1 = timeit("tuples.sort()", setup=setup, number=10000) | |
t2 = timeit("[deconcat_bitshift(n) for n in sorted(bits)]", setup=setup, number=10000) | |
print(f"naive_tuple: {t1:.3f}") | |
print(f"bitshift_tuple: {t2:.3f}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment