Last active
February 28, 2020 20:16
-
-
Save fridex/5fe1d8167f6ef94fa4b9419f90b41c15 to your computer and use it in GitHub Desktop.
Benchmark termial random
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
#!/usr/bin/env python3 | |
import math | |
import os | |
import random | |
import sys | |
import timeit | |
_ROUNDS = int(os.getenv("TERMIAL_DEFAULT_ROUNDS", 3)) | |
_ITERATIONS = int(os.getenv("TERMIAL_ITERATIONS", 1000000)) | |
_N = int(os.getenv("TERMIAL_N", 10000)) | |
def random_termial_v1(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
termial_of_n = ((n ** 2) + n) >> 1 | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def random_termial_v2(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
if n % 2: # or n & 1 | |
# odd numbers | |
nearest = n + 1 | |
termial_of_n = ((1 + nearest) * (nearest / 2)) - nearest | |
else: | |
termial_of_n = (1 + n) * (n / 2) | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def random_termial_v3(n: int) -> int: | |
"""Get index to an item from a list of size n. | |
The higher index of an item is, the lower probability of picking it. | |
""" | |
addition = (n * (n & 1)) | |
nearest = n + addition | |
termial_of_n = ((1 + nearest) * (nearest >> 1)) - addition | |
choice = random.randrange(termial_of_n) | |
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1))) | |
return n - 1 - i | |
def main(): | |
print("n = ", _N) | |
print("rounds = ", _ROUNDS) | |
print("iterations = ", _ITERATIONS) | |
print() | |
for i in range(_ROUNDS): | |
print(f">>> Round {i}") | |
for func in (random_termial_v1, random_termial_v2, random_termial_v3): | |
print( | |
"\t", | |
func.__name__, | |
": ", | |
timeit.timeit( | |
f"{func.__name__}({_N})", | |
number=_ITERATIONS, | |
globals=globals(), | |
), | |
) | |
__name__ == "__main__" and main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A sample output: