0

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.

wider93
  • 41
  • 2
  • unless you run into some specific problem, use whatever random generator you already use – lenik May 05 '20 at 04:46
  • What is 'better' depends on your definition of better - do you mean fastest, least CPU intensive, least memory usage, ... A "what is the best way to..."-question is generally not a suitable SO question. – Grismar May 05 '20 at 04:46
  • 1
    With speed as your concern, I'd recommend comparing performance using the standard library `timeit` and see what the difference is in your case and if that's enough to consider making the effort of changing it. – Grismar May 05 '20 at 05:01
  • 2
    Two related questions https://stackoverflow.com/questions/16138090/correct-way-to-generate-random-numbers-in-cython, https://stackoverflow.com/questions/40976880/canonical-way-to-generate-random-numbers-in-cython. – DavidW May 05 '20 at 05:37
  • Simply applying timeit to my whole code was not enough to compare because my functions are quite inconsistent. Yet I decided to leave as it anyway. RNG occupy only a small portion for now. – wider93 May 05 '20 at 06:47

0 Answers0