1

I have been looking for an exact Win implémentation of the patch of code below. I am not a great programmer and the code I have was initially in UNix but I have to modify it as little as possible for Win. I understand from some googling that the main problem is "gettimeofday" for which there no Win equivalent. Howver I would like to retain the same program structure as much as possible.

struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);    // ???
curtime = tv.tv_usec;
srand(tv.tv_usec); //time(&curtime)
Roalt
  • 8,330
  • 7
  • 41
  • 53
  • 2
    Normally `srand(time(0))` is enough, you don't really need sub-second resolution to seed the PRNG, unless you expect to start/stop the program several times per second. – Some programmer dude Sep 12 '12 at 14:57
  • Add an example of the output to a console of that function as if already existed on windowze or you where running from Unicse – umlcat Sep 12 '12 at 14:59
  • 1
    Do you clearly understand what this code does and why? If you just need to seed pseudo-random generator common way is to use current UTC time in seconds: `srand(time(NULL))`, it works both on UNIX and Windows. Why do you need `tv.tv_usec` that is just microseconds rest? – Rost Sep 12 '12 at 15:12
  • @Rost: The OP has most likely watched Stephan Lavavej's speech about `rand` on Channel 9, which among condemning `rand` alltogether makes `srand(time(0));` a big WTF, following the reasoning that all programs launched within the same second get the same seed (probably not a problem for most stuff, but he's technically kind of right). – Damon May 19 '14 at 09:57

2 Answers2

1

If you need the random seed as sub-second numbers, do something like this:

#ifdef WIN32
::srand( GetTickCount() );
#else
//your existing code
#endif
mark
  • 5,269
  • 2
  • 21
  • 34
1

you can use windows native function GetSystemTimeAsFileTime(), to get the time and write a wrapper to put it in struct timeval structure.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user2083050
  • 411
  • 4
  • 3