lundi 4 mai 2020

Fastest way to generate random integers in cython?

I'm writing a program that utilizes randomized behavior everywhere.

To illustrate, my code is like:

cdef int r = 8, c = 14

cdef class myclass1:
    pass

many_functions = [f1, f2, ..., f20, ...]
# Each functions are quite different in code structures,
# so I can't just generate one big random sequence and use them

cdef myclass1 x

old_container = [...] # contains many myclass1 instances

for _ in range(1000): #main loop
    new_container = []
    for x in old_container:
        func = random.choice(many_functions)
        new_container.append(func(x))
    old_container = new_container
# an example for f
cdef myclass1 f_n(myclass1 x):
    cdef int a, b, c
    a = random.randint(r)
    b = random.randint(c)
    c = random.randint(rc)
    # do something and return x

Currently I'm using numpy.random.Generator.integers whenever I need one or more random integers.

cdef int m
m = rng.integers(r)

I'm not sure this is the best way. Is it okay to use numpy.random even if I need small amount of rands each time? Could it be better to use just random.randint in pure python? Or is there any other better options I can choose?

*edit: speed is my only concern. Sorry for vague question.




Aucun commentaire:

Enregistrer un commentaire