From 598834255fd39f085286e7d75c46a6f012d22e6b Mon Sep 17 00:00:00 2001 From: Quinn Date: Thu, 19 Jun 2025 16:40:54 +0200 Subject: [PATCH] optimize some more by using /dev/random --- src/main.c | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/main.c b/src/main.c index 7135a15..6ebc07d 100644 --- a/src/main.c +++ b/src/main.c @@ -1,10 +1,9 @@ -#include #include #include #include #include #include -#include +#include #include #define error(ret, s, ...) \ @@ -17,14 +16,8 @@ typedef unsigned long long ull; int main(int argc, char** argv) { - // get the current time to set as the seed - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - srandom(ts.tv_nsec); - // return the result if no input - if (argc <= 1) - return printf("%s\n", (rand() & 1) ? "heads" : "tails"); + if (argc <= 1) return printf("%s\n", (rand() & 1) ? "heads" : "tails"); // loop through arguments for (unsigned i = 1; i < (unsigned)argc; ++i) { @@ -37,18 +30,20 @@ int main(int argc, char** argv) { ull headsc = 0; // amount of heads ull tailsc = 0; // amount of tails - while (c >= 31) { - c -= 31; - long n = random(); // generate a random number for this batch - int cnt = __builtin_popcountl(n); // counts the set bits + while (c >= (sizeof(ull) * 8)) { + c -= (sizeof(ull) * 8); + ull n; + getrandom(&n, sizeof(ull), GRND_INSECURE); + int cnt = __builtin_popcountll(n); // counts the set bits headsc += cnt; tailsc += 31 - cnt; } if (c > 0) { - long n = random(); + long n; + getrandom(&n, sizeof(ull), GRND_INSECURE); long msk = (1 << c) - 1; - int cnt = __builtin_popcountl(n & msk); + int cnt = __builtin_popcountll(n & msk); headsc += cnt; tailsc += c - cnt; }