Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am testing some code with some random numbers generated with the current time as the seed using

srand(time(0)) 

I'd like to get the same random numbers every time when I run it. So I want to set the value of current time to some predefined value temporarily just before running the program. And please don't ask me to remove random number temporarily as it is extremely essential.

Also, I don't have root access, so I can't set the date/time using the date command or its programmatic equivalent.

share|improve this question

4 Answers 4

up vote 1 down vote accepted

Use faketime.

faketime '2013-03-14 08:25:30' ./your_program

If you are not root, you may just download the program manually from your distribution. For example if you use a Debian derivative that uses APT:

aptitude download faketime
mkdir /tmp/faket/ dpkg-deb --extract faketime*.deb /tmp/faket
cp /tmp/faket/usr/bin/faketime ~
cp /tmp/faket/usr/lib/faketime/* ~
cd
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:."
./faketime '2013-03-14 08:25:30' ./your_program
share|improve this answer

Without root access you cannot set the time on the server. Also, when you say "I'd like to get the same random number everytime when i run it." you really are putting yourself in a hard spot of possibilities.

You cannot get the same random number repeatedly when running an app/script/etc. so the best thing you can do is generate a random number, and then use that statically every time you run the app for testing.

share|improve this answer

Without root access, you’re not going to be able to do what you ask; unless, perhaps, you could create a virtual machine (but then you’d need to be root on the VM).  Why not fake it out?

time_t time(time_t *dummy)
{
    return(atoi(getenv("FAKE_TIME")));
}

In other words, pick a value that you want to use as your seed for all your testing, and assign it to the environment variable FAKE_TIME.  Change the code back when you’re done testing.

Obviously, this is just an example; you can make the logic more intricate if you want.  (But if you’re seeding the random umber generator only once per program invocation, there probably isn’t any need to do so.)

share|improve this answer

Pass the seed as a configuration item, from the command line or from a config file.

It sounds to me extremely weird to obstinate about getting the random generator seed from the current time and then forcing it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.