// 007: what one Serial.println() costs the loop on UART0 (USB CDC On Boot: Disabled, the default).
// BAUD and TXBUF are passed with -D. HOLD=1: run the test with nobody reading, print results on 'r'.
#ifndef BAUD
#define BAUD 115200
#endif
#ifndef TXBUF
#define TXBUF 0
#endif
#ifndef HOLD
#define HOLD 0
#endif
#include "esp_timer.h"
#include <Preferences.h>   // HOLD=2: results go to NVS, printed on the next boot
#include "esp_cpu.h"

volatile float temp = 23.45f;     // volatile: no compile-time formatting
const int N_CALLS = 40;
uint32_t callCycles[N_CALLS];
char report[1024];
int rlen = 0;

static void rep(const char *fmt, ...) {
  va_list ap; va_start(ap, fmt);
  rlen += vsnprintf(report + rlen, sizeof(report) - rlen, fmt, ap);
  va_end(ap);
}

void setup() {
  if (TXBUF) Serial.setTxBufferSize(TXBUF);
  Serial.begin(BAUD);
#if HOLD == 2
  {
    Preferences pr; pr.begin("cost007", false);
    String saved = pr.getString("r", "");
    if (saved.length()) {            // second boot: print what the closed-port run measured
      pr.remove("r"); pr.end();
      delay(300);
      Serial.print("\n# results saved by the previous boot (port closed during the test):\n");
      Serial.print(saved);
      Serial.println("DONE");
      return;
    }
    pr.end();
  }
#endif
  delay(300);
  Serial.printf("# baud=%d txbuf=%d hold=%d cpu=%lu MHz\n", BAUD, TXBUF, HOLD, (unsigned long)getCpuFrequencyMhz());
  Serial.flush();
  delay(100);

  // 1. Baseline: empty loop body, 1 s
  uint32_t n = 0; int64_t t0 = esp_timer_get_time();
  while (esp_timer_get_time() - t0 < 1000000) { n++; }
  rep("RESULT baseline_loops_per_s=%lu\n", (unsigned long)n);

  // 2. Per-call cost of the first N_CALLS println() after the line has gone quiet
  Serial.flush(); delay(100);
  for (int i = 0; i < N_CALLS; i++) {
    uint32_t c0 = esp_cpu_get_cycle_count();
    Serial.print("temp: "); Serial.println(temp);
    callCycles[i] = esp_cpu_get_cycle_count() - c0;
  }
  Serial.flush(); delay(100);

  // 3. Steady state: loop that prints every iteration, 3 s
  uint32_t loops = 0; uint32_t cyc0 = esp_cpu_get_cycle_count(); t0 = esp_timer_get_time();
  while (esp_timer_get_time() - t0 < 3000000) {
    Serial.print("temp: "); Serial.println(temp);
    loops++;
  }
  int64_t dt = esp_timer_get_time() - t0; uint32_t dc = esp_cpu_get_cycle_count() - cyc0;
  Serial.flush();
  rep("RESULT print_loops=%lu in_us=%lld us_per_loop=%.2f cycles_per_loop=%.0f\n", (unsigned long)loops, dt,
      (double)dt / loops, (double)dc / loops);
  rep("RESULT first_calls_us=");
  for (int i = 0; i < N_CALLS; i++) rep("%.1f%s", callCycles[i] / (double)getCpuFrequencyMhz(), i + 1 < N_CALLS ? ";" : "\n");

#if HOLD == 2
  { Preferences pr; pr.begin("cost007", false); pr.putString("r", report); pr.end(); }
  return;
#endif
  if (HOLD) { while (Serial.read() != 'r') delay(10); }
  delay(200);
  Serial.print("\n");
  Serial.print(report);
  Serial.println("DONE");
}

void loop() {}
