首页 > 解决方案 > 在 cython 中生成随机整数的最快方法?

问题描述

我正在编写一个在任何地方都使用随机行为的程序。

为了说明,我的代码如下:

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

目前,numpy.random.Generator.integers每当我需要一个或多个随机整数时,我都会使用它。

cdef int m
m = rng.integers(r)

我不确定这是最好的方法。即使我每次需要少量兰特,也可以使用 numpy.random 吗?在纯 python 中只使用 random.randint 会更好吗?或者我还有其他更好的选择吗?

*编辑:速度是我唯一关心的。对不起,含糊的问题。

标签: pythonrandomcython

解决方案


推荐阅读