On NumPy with np.argsort - In : timeit.timeit( 'np.random.rand(138).argsort()', setup='import numpy as np', number=1000000) On NumPy with np.argpartition - In : timeit.timeit( 'np.random.rand(138).argpartition(range(4))', setup='import numpy as np', number=1000000) Let's time these two versions for performance comparison against the MATLAB version. Or with np.argsort like so - np.random.rand(138).argsort() NumPy's np.random.choice(138,4, replace=False) with np.argpartition as : np.random.rand(138).argpartition(range(4)) (string vs lambda doesn't make a noticeable difference)īased on this solution that showed how one can simulate np.random.choice(., replace=False)'s behavior with a trick based on argsort/ argpartition, you can recreate MATLAB's randperm(138,4), i.e. That's about 22 times faster than the original: > timeit.timeit('permutation(138)', setup='from numpy.random import permutation', number=1000000) Update 2: Since NumPy's random function appears to be much faster, I tried this and it's another factor ~1.33 faster: > def four(): Update 1: At first I used random.randrange, but np.random.randint made the whole thing about twice as fast. Return (a, b, c, d) if a != b and a != c and a != d and b != c and b != d and c != d else four() How long does this take for you? I estimate 1-2 seconds.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |