#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <time.h>

#ifndef ITERS_DEFAULT
#define ITERS_DEFAULT 1000000
#endif

static double now_seconds(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec + ts.tv_nsec * 1e-9;
}

int main(int argc, char **argv) {
    uint64_t iters = ITERS_DEFAULT;
    for (int i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "--iters") == 0 && i+1 < argc) {
            iters = strtoull(argv[i+1], NULL, 10);
            i++;
        }
    }

    double t0 = now_seconds();

    volatile double x = 0.123456789; // volatile to avoid optimizing away
    for (uint64_t i = 0; i < iters; ++i) {
        // A small RK4-like microkernel combining trig, sqrt, and muls
        double k1 = sin(x) * 0.5 + cos(x * 0.7);
        double k2 = sqrt(fabs(k1)) * 0.7 + sin(k1*0.3);
        double k3 = k2 * 0.333 + cos(k2*1.3);
        double k4 = (k1 + k2 + k3) * 0.25;
        x += (k1 + 2.0*k2 + 2.0*k3 + k4) * 0.0625;
        // small nonlinear coupling
        x = fmod(x * 1.0000001 + 1e-12, 1000.0);
    }

    double t1 = now_seconds();
    double elapsed = t1 - t0;
    double ops_per_sec = iters / elapsed;

    printf("bench_opt: iters=%llu elapsed=%.6fs ops/sec=%.0f final_x=%.12f\n",
           (unsigned long long)iters, elapsed, ops_per_sec, (double)x);

    return 0;
}
