import numba as nbimport numpy as npfrom threading import Thread
n = 500_000draws = np.random.randint(low=1, high=10, size=n)seeds = np.arange(n)
@nb.jit([nb.float64(nb.int32, nb.int32)], nogil=True, nopython=True)def kernel(seed, n_draws): np.random.seed(seed) r = np.random.uniform(0, 1, 1)[0] for _ in range(n_draws**2): r = np.random.uniform(0, 1, 1)[0] return r
@nb.jit(nb.void(nb.int32[:], nb.int32[:], nb.float64[:]), nopython=True, nogil=True)def worker1(seeds, draws, out): assert len(seeds) == len(draws) assert len(seeds) == len(out) for i in range(len(out)): out[i] = kernel(seeds[i], draws[i])
def manager1(seeds, draws, n_threads=8): assert len(seeds) == len(draws) n = len(seeds) out = np.zeros(n, dtype='f8') seed_chunks = np.array_split(seeds, n_threads, axis=0) draws_chunks = np.array_split(draws, n_threads, axis=0) out_chunks = np.array_split(out, n_threads, axis=0) threads = [Thread(target=worker1, args=[seed_chunks[i], draws_chunks[i], out_chunks[i]]) for i in range(n_threads)] for t in threads: t.start() for t in threads: t.join() return out
@nb.jit(nb.float64[:](nb.int32[:], nb.int32[:]), nopython=True, nogil=True, parallel=True)def manager2(seeds, draws): assert len(seeds) == len(draws) n = len(seeds) out = np.zeros(n, dtype=np.float64) for i in nb.prange(n): out[i] = kernel(seeds[i], draws[i]) return out
%%timeittest1 = manager1(seeds, draws)
>> 1.77 s ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeittest2 = manager2(seeds, draws)
>> 1.77 s ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
--
You received this message because you are subscribed to the Google Groups "Numba Public Discussion - Public" group.
To unsubscribe from this group and stop receiving emails from it, send an email to numba-users+unsubscribe@continuum.io.
To post to this group, send email to numba...@continuum.io.
To view this discussion on the web visit https://groups.google.com/a/continuum.io/d/msgid/numba-users/cb9ac326-6e00-4ec2-9a7b-102129d0c1cc%40continuum.io.
For more options, visit https://groups.google.com/a/continuum.io/d/optout.