jeudi 7 septembre 2023

Random integer generation performance optimization

I am looking to generate random integers on the interval [0, n) as fast as possible:

from random import Random

rand = Random(123)

def rand_func(max: int, random: Random):
    return int(random.random() * max)

for a in range(10_000_000):                 # perf_counter 9.7s
    ax = rand_func(456, rand)

for b in range(10_000_000):                 # perf_counter 3.9s
    bx = int(rand.random() * 456)

My experience in other languages leaves me surprised at how expensive this function call seems to be.

Is there a method, pattern or decorator I could use to further optimize speed while keeping the code simple and usable?

I've looked at some other less simple solutions. numpy random.integers is very fast at returning a large array of results, but consuming the results becomes more complex and less ideal.

(Of note I'm aware of the bias in the random integer sampling method above but it is acceptable for my requirements).




Aucun commentaire:

Enregistrer un commentaire