mardi 10 mars 2020

Why random.choices is faster than NumPy’s random choice?

I am trying to do random sampling in the most efficient way in Python, however, I am puzzled because when using the numpy's random.choices() was slower than using the random.choices()

import numpy as np
import random

np.random.seed(12345)

# use gamma distribution
shape, scale = 2.0, 2.0 
s = np.random.gamma(shape, scale, 1000000)
meansample = []

samplesize = 500

%timeit meansample = [ np.mean( np.random.choice( s, samplesize, replace=False)) for _ in range(500)]
23.3 s ± 229 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit meansample = [np.mean(random.choices(s, k=samplesize)) for x in range(0,500)]
152 ms ± 324 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

23 Seconds vs 152 ms is a lot of time

What i'am doing wrong?




Aucun commentaire:

Enregistrer un commentaire