Reputation: 91
I am trying to write a program that generates a random number based on the internal clock of the system, in such a way that I don't need a seed nor a first value. The first value must be taken from the internal clock by converting year, month, day, hours, minutes, seconds to milliseconds and adding them to the current millisecond in order to get a unique number (Time Stamp). Any help to get these values in C?
Upvotes: 5
Views: 5140
Reputation: 3302
If you happen to be doing this in Windows you can use:
unsigned int rand = GetTickCount() % A_PRIME_NUMBER_FOR_EXAMPLE;
[Edit: emphasise modulo something appropriate for your circumstances]
Upvotes: 0
Reputation: 753775
You can use either clock_gettime()
or
gettimeofday()
— or, if you're in a really impoverished environment, ftime()
or time()
.
Make sure you're using a big enough data type to hold the millitime.
For clock_gettime()
, the result is a struct timespec
with elements tv_sec
and tv_nsec
. You'd use:
#include <time.h>
#include <stdint.h>
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
int64_t millitime = t.tv_sec * INT64_C(1000) + t.tv_nsec / 1000000;
With gettimeofday()
(which is officially deprecated, but is more widely available — for example, Mac OS X has gettimeofday()
but does not have clock_gettime()
), you have a struct timeval
with members tv_sec
and tv_usec
:
#include <sys/time.h>
#include <stdint.h>
struct timeval t;
gettimeofday(&t, 0);
int64_t millitime = t.tv_sec * INT64_C(1000) + t.tv_usec / 1000;
(Note that ftime()
was standard in older versions of POSIX but is no longer part of POSIX, though some systems will still provide it for backwards compatibility. It was available in early versions of Unix as the first sub-second time facility, but not as early as 7th Edition Unix. It was added to POSIX (Single Unix Specification) for backwards compatibility, but you should aim to use clock_gettime()
if you can and gettimeofday()
if you can't.)
Upvotes: 6
Reputation: 108938
Standard C does not guarantee time accuracy better than a second. If you're on a POSIX system, try the clock* functions.
Upvotes: 0