crandomtimespec

Viability of using the "tv_nsec" nanosecond component returned by "timespec_get()" on Linux as random number generator in C?


With the following simple code snippet:

struct timespec ts;
for (int i = 0; i < 100; i++) {
    timespec_get(&ts, TIME_UTC);
    printf("%ld, ", ts.tv_nsec % 100);
}

I get output like this:

58, 1, 74, 49, 5, 59, 89, 20, 52, 86, 17, 48, 79, 10, 41, 73, 3, 40, 72, 3, 36, 67, 98, 30, 61, 92, 24, 55, 86, 17, 49, 82, 14, 45, 76, 7, 40, 72, 3, 36, 71, 2, 35, 66, 97, 28, 66, 97, 28, 60, 90, 22, 52, 83, 15, 46, 77, 7, 41, 72, 3, 36, 67, 0, 44, 17, 82, 13, 45, 77, 8, 59, 90, 22, 54, 85, 17, 48, 80, 12, 43, 75, 6, 57, 89, 20, 52, 84, 15, 47, 79, 14, 50, 82, 16, 47, 79, 11, 43, 74,

I haven't studied the statistical distribution of the numbers and my searches have turned up blank, but the output does at first glance look similar to output of rand() or random(). Has anyone studied this or is able to express an opinion - could timespec_get() be used as random number generator? Would it be pseudo random or not? Why?


Solution

  • could timespec_get() be used as random number generator?

    Of course. But that doesn't mean the output of such a RNG would have desirable or even acceptable statistical properties.

    In particular, successive outputs are strongly correlated with each other. Your example hides that, somewhat, by discarding all the most-significant decimal digits. Additionally, the system clock is not required to have single-nanosecond resolution, though yours seems to have. In a system that didn`t have such resolution, the least-significant digits of all results would likely be correlated, and their distribution non-uniform.

    Would it be pseudo random or not? Why?

    No, actually. The output of a PRNG is deterministic with respect to the runtime state of the calling program at the time of the call. timespec_get(), on the other hand, depends on the program's execution context, not its own state.