optimize some more by using /dev/random
This commit is contained in:
25
src/main.c
25
src/main.c
@@ -1,10 +1,9 @@
|
||||
#include <bits/time.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/random.h>
|
||||
#include <time.h>
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user