1

I know that time(0) will return in seconds, but is there a way for it to return smaller values? I think they are called miliseconds, but not sure. I need to pass it for srand().

Reason is I made 2 threads communicate with each other, but they communicate so fast, that each second they send like 30 same message to each other and I need those random numbers to be different, so a different seed each "milisecond"

2

5 Answers 5

2

Seems your error is you are trying to call srand() more than once.

See this question for a detailed explaination: srand() -- why call only once?

1
  • Ah, I get it. I was generating the same seed for ~30 times in the same second. Commented Mar 29, 2014 at 23:01
0

Assuming you are on a POSIX-compliant environment, you can use gettimeofday

struct timeval tv;
suseconds_t microseconds;

gettimeofday(tv, NULL);

microseconds = tv.tv_usec;
0

What you are asking is entirely system dependent. In the old days, most systems did time in milliseconds. For example, the VMS operating system used 8-byte times with millisecond increments.

When Unix became popular, libraries started following it by using seconds.

You can get milliseconds on posix as described above. Apple also has NSDate and CACurrentMediaTime. Windoze has GetTickCount and some others.

0

If you need two threads to communicate using pseudo-random numbers, you should use two independent streams, each seeded only once with different random seeds. There are many C/C++ libraries that can do this, but using standard C rand/srand isn't one of them. Even if you correctly call srand() only once, using the same random stream in both threads will cause predictable (i.e. nonrandom) behavior.

Use a better generator, and seed it with some real system randomness--that's /dev/random on real computers, CryptGenRandom on Windows.

-1

There is not standard C/C++ function for this. But usually OS provides such function.

There is function gettimeofday, in Linux. and there is function GetSystemTime on Windows.

http://linux.die.net/man/2/gettimeofday http://msdn.microsoft.com/en-us/library/windows/desktop/ms724390(v=vs.85).aspx

maybe there are some other functions....

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