fully reoptimize

This commit is contained in:
2025-06-17 23:28:21 +02:00
parent deabe97247
commit 95dce84d28
2 changed files with 17 additions and 18 deletions

View File

@@ -1,5 +1,5 @@
CC ?= cc
CFLAGS += -Wall -Wextra -Wpedantic -O2 -MD -MP -std=gnu99
CFLAGS += -Wall -Wextra -Wpedantic -O3 -MD -MP -std=gnu99
LDFLAGS +=
SRC = $(shell find src/ -name '*.c')

View File

@@ -4,6 +4,7 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#define error(ret, s, ...) \
@@ -14,10 +15,6 @@
typedef unsigned long long ull;
/* acquires the random data */
long rdat(void) {
return random();
}
int main(int argc, char** argv) {
// get the current time to set as the seed
@@ -26,8 +23,8 @@ int main(int argc, char** argv) {
srandom(ts.tv_nsec);
// return the result if no input
if (argc <= 1) return printf("%s\n", (random() & 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) {
@@ -35,23 +32,25 @@ int main(int argc, char** argv) {
errno = 0;
ull c = strtoull(argv[i], NULL, 10);
if (errno != 0) error(errno, "parse error for string: '%s'\n", argv[i]);
if (c < 1 || c > (ULLONG_MAX - 1)) error(1, "count may only be in between 1 and %llu. Received %llu\n", ULLONG_MAX - 1, c);
// perform for the input count
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
headsc += cnt;
tailsc += 31 - cnt;
}
for (ull j = 0; j < c; ++j) {
ull n = rdat();
#if defined(__GNUC__) && __GNUC__ >= 8
# pragma GCC unroll 31
#elif defined(__clang__)
# pragma unroll 31
#endif
for (ull b = 1; b <= INT32_MAX; b <<= 1)
(void)((n & b) ? headsc++ : tailsc++); // increment the correct counter
if (c > 0) {
long n = random();
long msk = (1 << c) - 1;
int cnt = __builtin_popcountl(n & msk);
headsc += cnt;
tailsc += c - cnt;
}
// print the results of this cycle