Take the 2-minute tour ×

I am iterating a perl script in a for loop and using srand(time¦$$) in my script to seed random numbers.

In my output I get repeated results when I get individual results if I do them one at a time instead of using the for loop. Is this because of the srand line? Any suggestions?


share|improve this question
srand should be called once per program unless you're voluntarily wanting to get the same run of random numbers multiple times. –  Mat Sep 1 '12 at 10:48
I don't want to get the same run of random numbers. I stuck all my code in a for loop, which works but I get consecutive repeats in the output –  user1637359 Sep 1 '12 at 10:51
Then make sure you only call srand once (or not at all in fact). Move that call out of the loop. –  Mat Sep 1 '12 at 10:52
You shouldn't use srand at all if you want a different sequence each time. It is meant for providing random but reproducible data so that runs can be duplicated. Perl provides a very effective random seed internally as long as you don't call srand yourself. –  Borodin Sep 1 '12 at 16:57
@Mat, I dare say, you shouldn't call srand ever, but if you do, it shouldn't be more than one per process. –  ikegami Sep 1 '12 at 19:49
add comment

2 Answers

Not an expert in Perl, but this is definitely due to one iteration of the loop being faster than 1 ms, so the srand function is called multiple times with the same seed value. You should initialize the random number generator outside of the for loop (or omit it entirely); inside the loop, just use rand.

share|improve this answer
time has a resolution of 1s, not 1ms, therefore it's actually much worse: calling srand more than once within the same second suffices. –  Moritz Bunkus Sep 1 '12 at 10:54
add comment

Calls to srand with the same number result in the same sequence of numbers returned by the following rand calls. So if you do srand(time() | $$) in quick succession (e.g. within the very same second) then you're doing exactly that: calling srand with the same values resulting in the same sequences generated by rand.

See the perldoc page to srand.

One thing the documentation also mentions is that if you call rand without calling srand first then Perl will actually call srand for you. Therefore you don't really need the call to srand in your script in the first place.

The documentation also strongly advises against calling srand more than once per process because that results in loss of entropy.

share|improve this answer
Thanks! It works now!! –  user1637359 Sep 1 '12 at 10:58
add comment

Your Answer


