Don’t do srand(time(0)) while testing!

This is my smallest post, but extremely important. In C or C++, before generating random numbers we often end up doing

srand(time(0))

So every time you run the program, you get new set of random numbers. Do you see the problem?

The problem is that the output is not reproducible. This is a big issue if you want to debug a particular test case.

But for some purposes, you just don’t need to reproduce output, in that case go ahead and use it. In some of my (blog) programs I am guilty of using srand(time(0)), please disregard it.

About these ads
This entry was posted in Programming and tagged . Bookmark the permalink.

2 Responses to Don’t do srand(time(0)) while testing!

  1. Mukul Gupta says:

    Something that is random ought not be reproducible. It is the very reason, I’d like to use srand(time(NULL))

    • vinayakgarg says:

      Random numbers do need to be reproducible while testing. Otherwise it becomes impossible to isolate the bug caused by some special case and debug it.

      Apart from this we pretty much don’t want reproduce-ability.
      I think I will change the title of article :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s