多线程生成

四核分布 (randomstandard_normalstandard_exponentialstandard_gamma )所有这些都允许使用 out 关键字参数。现有的数组需要是连续的和行为良好的(可写的和对齐的)。在正常情况下,数组是使用公共构造函数创建的,例如 numpy.empty 将满足这些要求。

这个例子使用了python3 concurrent.futures 使用多个线程填充数组。线程是长寿命的,因此重复调用不需要从线程创建中产生任何额外的开销。

在给定线程数不变的情况下,从相同种子将产生相同输出的意义上讲,生成的随机数是可再现的。

from numpy.random import default_rng, SeedSequence
import multiprocessing
import concurrent.futures
import numpy as np

class MultithreadedRNG:
    def __init__(self, n, seed=None, threads=None):
        if threads is None:
            threads = multiprocessing.cpu_count()
        self.threads = threads

        seq = SeedSequence(seed)
        self._random_generators = [default_rng(s)
                                   for s in seq.spawn(threads)]

        self.n = n
        self.executor = concurrent.futures.ThreadPoolExecutor(threads)
        self.values = np.empty(n)
        self.step = np.ceil(n / threads).astype(np.int_)

    def fill(self):
        def _fill(random_state, out, first, last):
            random_state.standard_normal(out=out[first:last])

        futures = {}
        for i in range(self.threads):
            args = (_fill,
                    self._random_generators[i],
                    self.values,
                    i * self.step,
                    (i + 1) * self.step)
            futures[self.executor.submit(*args)] = i
        concurrent.futures.wait(futures)

    def __del__(self):
        self.executor.shutdown(False)

多线程随机数生成器可用于填充数组。这个 values 属性显示填充前的零值和填充后的随机值。

In [2]: mrng = MultithreadedRNG(10000000, seed=12345)
   ...: print(mrng.values[-1])
Out[2]: 0.0

In [3]: mrng.fill()
   ...: print(mrng.values[-1])
Out[3]: 2.4545724517479104

使用多个线程生成所需的时间可以与使用单个线程生成所需的时间进行比较。

In [4]: print(mrng.threads)
   ...: %timeit mrng.fill()

Out[4]: 4
   ...: 32.8 ms ± 2.71 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

单线程调用直接使用位生成器。

In [5]: values = np.empty(10000000)
   ...: rg = default_rng()
   ...: %timeit rg.standard_normal(out=values)

Out[5]: 99.6 ms ± 222 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

增益是可观的,即使是对于只有中等大小的阵列,缩放也是合理的。由于数组创建开销,与不使用现有数组的调用相比,收益更大。

In [6]: rg = default_rng()
   ...: %timeit rg.standard_normal(10000000)

Out[6]: 125 ms ± 309 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

注意如果 threads 不是由用户设置的,它将由 multiprocessing.cpu_count() .

In [7]: # simulate the behavior for `threads=None`, if the machine had only one thread
   ...: mrng = MultithreadedRNG(10000000, seed=12345, threads=1)
   ...: print(mrng.values[-1])
Out[7]: 1.1800150052158556