optimize some more by using /dev/random

This commit is contained in:
2025-06-19 16:40:54 +02:00
parent 5f6f1bf720
commit 598834255f

View File

@@ -1,10 +1,9 @@
#include <bits/time.h>
#include <errno.h> #include <errno.h>
#include <limits.h> #include <limits.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/types.h> #include <sys/random.h>
#include <time.h> #include <time.h>
#define error(ret, s, ...) \ #define error(ret, s, ...) \
@@ -17,14 +16,8 @@ typedef unsigned long long ull;
int main(int argc, char** argv) { 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 // return the result if no input
if (argc <= 1) if (argc <= 1) return printf("%s\n", (rand() & 1) ? "heads" : "tails");
return printf("%s\n", (rand() & 1) ? "heads" : "tails");
// loop through arguments // loop through arguments
for (unsigned i = 1; i < (unsigned)argc; ++i) { 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 headsc = 0; // amount of heads
ull tailsc = 0; // amount of tails ull tailsc = 0; // amount of tails
while (c >= 31) { while (c >= (sizeof(ull) * 8)) {
c -= 31; c -= (sizeof(ull) * 8);
long n = random(); // generate a random number for this batch ull n;
int cnt = __builtin_popcountl(n); // counts the set bits getrandom(&n, sizeof(ull), GRND_INSECURE);
int cnt = __builtin_popcountll(n); // counts the set bits
headsc += cnt; headsc += cnt;
tailsc += 31 - cnt; tailsc += 31 - cnt;
} }
if (c > 0) { if (c > 0) {
long n = random(); long n;
getrandom(&n, sizeof(ull), GRND_INSECURE);
long msk = (1 << c) - 1; long msk = (1 << c) - 1;
int cnt = __builtin_popcountl(n & msk); int cnt = __builtin_popcountll(n & msk);
headsc += cnt; headsc += cnt;
tailsc += c - cnt; tailsc += c - cnt;
} }