Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

rand() warmup

Name: Anonymous 2012-01-20 16:28

void init_random() {
    clock_t start = clock();
    int i = 0;
    while (clock() - start == 0) {
        i++;
    }
    srand(time(0) + i);
}


17±3 ms
Is it okay?

Name: Anonymous 2012-01-20 20:45

looping until the clock changes is a pointless waste of CPU time and a battery drainer for mobile devices.

clock may have a varying granularity which could be very fine or very poor.

for instance what if it is linked to a 100 hz interrupt timer? then you're burning 10 milliseconds, which is eons in modern computing cycles. (how often will your program run; is it scripted?)

OTOH if the clock is very fine, maybe your i++ will never execute b/c it may take longer to call clock than the time between successive values.

here are some other ideas. forget about strictly standard C and help yourself to some additional functions. for instance, you could call the POSIX gettimeofday, or even the newer clock_gettime to get a finer grained real time with microseconds or nanoseconds.  you could get the process id with getpid and mix that in also.

on windoze you have GetTickCount which is milliseconds since the system started (not process virtual time like clock). I think mingw has gettimeofday.

Name: Anonymous 2012-01-20 20:49

>>8

sorry, that's a poor idea. /dev/random is a source of real randomness. so that means two things.

one, you're wasting  good random numbers on seeding this POS  prng in the standard C library which is not suitable for any applications that actually need real randomness, like crypto.

secondly /dev/random is a blocking device on linux. it will pause your program if not enough random bits are available until the system gathers enough. by stealing these bits, you make other programs block, ones which need it, like crypto stuff.

you want /dev/urandom, which is a nonblocking device that produces a sequence of pseudo-random bytes seeded from random bytes.

Name: Anonymous 2012-01-20 20:52

>>7

there is no guarantee that the uninitialized variable provides useful random bits.  it is very possible that it may have the same behavior each time your run the program and so it adds nothing. i.e. you're not necessarily overcoming the problem that time(NULL) may return the same number when the program is run several times in a script.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List