Reputation: 2962
I am running a process which is massively parallelized that depends on randomness. The trouble is that each of the workers in the parallel process shares the same random seed as the parent process, thereby ruining my attempts to run distinct random simulations.
Thus, I have the problem of how to set a distinct random seed on each worker at inception. My current solution is to take the microseconds part off of time.time()
and convert it to an integer before passing it to random.seed()
. It looks like the following. Is there a better way?
import re
import random
import time
def set_random_seed():
seed = int(re.sub(r'[^0-9]', '', str(time.time())[-7:]))
random.seed(seed)
Upvotes: 0
Views: 1947
Reputation: 18320
See: https://docs.python.org/3/library/random.html#random.seed
If the seed is omitted os.urandom will be used - if available. You can just call:
random.seed()
If you are worried about unlikely case of os.urandom
being not available, generate unique seeds in your main process and pass one to each process you start.
Upvotes: 4