dimanche 14 janvier 2018

Numpy random number generation runs slower after being vectorised

I have noticed that attempting to speed up numpy code that involves generating large numbers of random numbers by vectorising the python for loops out can have the opposite result and can slow it down. The output of the following bit of code is: took time 0.588 and took time 0.789. This goes against my intuition for how to best write numpy code and I was wondering why this would be the case?

import time
import numpy as np

N = 50000
M = 1000
repeats = 10

start = time.time()
for i in range(repeats):
    for j in range(M):
        r = np.random.randint(0,N,size=N)
print 'took time ',(time.time()-start)/repeats

start = time.time()
for i in range(repeats):
    r = np.random.randint(0,N,size=(N,M))
print 'took time ',(time.time()-start)/repeats




Aucun commentaire:

Enregistrer un commentaire