6

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.

5 Answers 5

7

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
0

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.

0

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.)

0

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.

-1

If using ntpd (check with service ntpd status):

service ntpd stop
date --set="23 June 1988 22:22:55"

When done:

ntpd -gq
service ntpd start

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .