// ESP32-S3 vs Arduino Uno. One sketch for both boards.
// Uno:  arduino:avr:uno            (arduino:avr 1.8.8)
// S3:   esp32:esp32:esp32s3        (esp32:esp32 3.3.12), default settings
//
// Method:
//  * every arithmetic probe is a chain of dependent operations (each one waits
//    for the result of the previous one), 1000 operations per call
//    (100 iterations x 10 in a row);
//  * BAR(x) is an empty asm statement: the compiler "forgets" the value of x and
//    cannot fold the chain into a constant, but no extra instructions are added;
//  * the call is repeated K times, K doubles until a measurement takes >= 100 ms;
//    then 3 runs, the minimum is taken. Time comes from micros().
//  * loop overhead is measured by the "base" probes and subtracted on the PC.
// Output: lines "R,<group>,<name>,<K>,<ops per call>,<us>". Everything else is info.

#include <string.h>
#if defined(__AVR__)
  #define BOARD_NAME "Arduino Uno (ATmega328P)"
  #define BAR(x)  asm volatile("" : "+r"(x))
  #define BARF(x) asm volatile("" : "+r"(x))
  #define TEST_PIN 13
  #define FAST_SET()  (PORTB |=  _BV(5))   // D13 = PB5
  #define FAST_CLR()  (PORTB &= ~_BV(5))
#else
  #include "soc/gpio_reg.h"
  #include "driver/dedic_gpio.h"
  #include "hal/dedic_gpio_cpu_ll.h"
  #define BOARD_NAME "ESP32-S3"
  #define BAR(x)  asm volatile("" : "+r"(x))
  #define BARF(x) asm volatile("" : "+f"(x))   // float in an FPU register
  #define TEST_PIN 4
  #define FAST_SET()  REG_WRITE(GPIO_OUT_W1TS_REG, 1u << TEST_PIN)
  #define FAST_CLR()  REG_WRITE(GPIO_OUT_W1TC_REG, 1u << TEST_PIN)
#endif

#define REP10(s) s s s s s s s s s s
#define REP5(s)  s s s s s

volatile uint32_t sink32;
volatile float    sinkf;
volatile double   sinkd;

// ---------- probe templates ----------
#define TEST_INT(fname, T, X0, Y0, OP)                                   \
  __attribute__((noinline)) void fname() {                               \
    T x = X0, y = Y0; BAR(x); BAR(y);                                    \
    for (uint8_t i = 0; i < 100; i++) { REP10(OP; BAR(x);) }             \
    sink32 = x;                                                          \
  }
#define TEST_FLT(fname, X0, Y0, OP)                                      \
  __attribute__((noinline)) void fname() {                               \
    float x = X0, y = Y0; BARF(x); BARF(y);                              \
    for (uint8_t i = 0; i < 100; i++) { REP10(OP; BARF(x);) }            \
    sinkf = x;                                                           \
  }
#define TEST_DBL(fname, X0, Y0, OP)                                      \
  __attribute__((noinline)) void fname() {                               \
    double x = X0, y = Y0; BAR(x); BAR(y);                               \
    for (uint8_t i = 0; i < 100; i++) { REP10(OP; BAR(x);) }             \
    sinkd = x;                                                           \
  }

// empty loop with the same barriers: the overhead
TEST_INT(base_int, uint32_t, 1, 1, )
TEST_FLT(base_flt, 1.0f, 1.0f, )

// Round 1: integers
TEST_INT(add_u8,  uint8_t,  1, 3, x = x + y)
TEST_INT(add_u16, uint16_t, 1, 3, x = x + y)
TEST_INT(add_u32, uint32_t, 1, 3, x = x + y)
TEST_INT(mul_u8,  uint8_t,  1, 3, x = x * y)
TEST_INT(mul_u16, uint16_t, 1, 3, x = x * y)
TEST_INT(mul_u32, uint32_t, 1, 3, x = x * y)
// division: x -> y / x, the values alternate (300 <-> 200) and do not degenerate
TEST_INT(div_u16, uint16_t, 300,  60000,   x = y / x)
TEST_INT(div_u32, uint32_t, 1234, 1000000, x = y / x)
// "int" as sketches use it: 16 bits on AVR, 32 bits on ESP32-S3
TEST_INT(add_int, int, 1, 3, x = x + y)
TEST_INT(mul_int, int, 1, 3, x = x * y)

// Round 2: float (the values do not reach inf/0 within 1000 operations)
TEST_FLT(add_f, 1.0f, 0.001f,   x = x + y)
TEST_FLT(mul_f, 1.0f, 1.0001f,  x = x * y)
TEST_FLT(div_f, 3.0f, 10.0f,    x = y / x)
TEST_FLT(sin_f, 1.0f, 0.5f,     x = sin(x) + y)   // sin(float) in C++
TEST_DBL(mul_d, 1.0,  1.0001,   x = x * y)        // double: 32 bits on AVR

// Round 3: GPIO. 1000 calls per probe.
__attribute__((noinline)) void dw() {
  for (uint8_t i = 0; i < 100; i++) {
    REP5(digitalWrite(TEST_PIN, HIGH); digitalWrite(TEST_PIN, LOW);)
  }
}
__attribute__((noinline)) void dw_fast() {
  for (uint8_t i = 0; i < 100; i++) { REP5(FAST_SET(); FAST_CLR();) }
}
#if !defined(__AVR__)
// ESP32-S3: "dedicated GPIO", the pin is driven by a CPU instruction
__attribute__((noinline)) void dw_dedic() {
  for (uint8_t i = 0; i < 100; i++) {
    REP5(dedic_gpio_cpu_ll_write_mask(1, 1); dedic_gpio_cpu_ll_write_mask(1, 0);)
  }
}
#endif
__attribute__((noinline)) void base_loop() {
  for (uint8_t i = 0; i < 100; i++) { REP10(asm volatile("");) }
}

// Round 5: arrays (512 bytes each: the Uno has only 2 KB of RAM)
#define ARR_BYTES 512
uint32_t buf32[ARR_BYTES / 4];
uint8_t  dst[ARR_BYTES];
__attribute__((noinline)) void arr_sum_u8() {      // int sum over bytes
  const uint8_t *b = (const uint8_t *)buf32;
  int s = 0;
  for (int i = 0; i < ARR_BYTES; i++) s += b[i];
  sink32 = s;
}
__attribute__((noinline)) void arr_sum_u32() {     // sum of 128 32-bit words
  uint32_t s = 0;
  for (int i = 0; i < ARR_BYTES / 4; i++) s += buf32[i];
  sink32 = s;
}
__attribute__((noinline)) void arr_memcpy() {
  memcpy(dst, buf32, ARR_BYTES);
  asm volatile("" :: "r"(dst) : "memory");   // without this, LTO removes the copy
  sink32 = dst[ARR_BYTES - 1];
}

// Round 4: printing to "nowhere", only the cost of formatting
class NullPrint : public Print {
 public:
  size_t write(uint8_t) override { return 1; }
  size_t write(const uint8_t *, size_t n) override { return n; }
};
NullPrint nullp;
volatile float pf = 23.456f;   // volatile: otherwise LTO on the Uno does the printing at compile time
volatile long  pl = 123456L;
__attribute__((noinline)) void fmt_float() { for (uint8_t i = 0; i < 10; i++) nullp.println(pf, 2); }
__attribute__((noinline)) void fmt_long()  { for (uint8_t i = 0; i < 10; i++) nullp.println(pl); }

// ---------- harness ----------
#define TARGET_US 100000UL
void measure(const __FlashStringHelper *group, const __FlashStringHelper *name,
             void (*fn)(), uint16_t ops) {
  fn();                                   // warm-up (flash cache on the ESP32-S3)
  uint32_t K = 1, dt;
  for (;;) {
    uint32_t t0 = micros();
    for (uint32_t k = 0; k < K; k++) fn();
    dt = micros() - t0;
    if (dt >= TARGET_US) break;
    K *= 2;
  }
  uint32_t best = dt;
  for (uint8_t r = 0; r < 3; r++) {
    uint32_t t0 = micros();
    for (uint32_t k = 0; k < K; k++) fn();
    dt = micros() - t0;
    if (dt < best) best = dt;
  }
  Serial.print(F("R,")); Serial.print(group); Serial.print(',');
  Serial.print(name);    Serial.print(',');
  Serial.print(K);       Serial.print(',');
  Serial.print(ops);     Serial.print(',');
  Serial.println(best);
  Serial.flush();
}
#define M(g, f, ops) measure(F(g), F(#f), f, ops)

// Serial: a ~2000-byte stream and the return time of one short print()
void serial_tests() {
  static const char line[] PROGMEM = "#.............................................\n";
  Serial.flush();
  uint32_t t0 = micros();
  for (uint8_t i = 0; i < 42; i++) Serial.print((const __FlashStringHelper *)line);
  Serial.flush();
  uint32_t dt = micros() - t0;
  Serial.print(F("R,serial,stream,1,")); Serial.print(42 * strlen_P(line));
  Serial.print(','); Serial.println(dt);

  uint32_t best = 0xFFFFFFFF;
  for (uint8_t r = 0; r < 5; r++) {
    Serial.flush();
    t0 = micros();
    Serial.print(F("#Temperature: 23.5 C\n"));          // 21 bytes
    dt = micros() - t0;
    if (dt < best) best = dt;
  }
  Serial.flush();
  Serial.print(F("R,serial,print_21B_return,1,1,")); Serial.println(best);

  best = 0xFFFFFFFF;
  for (uint8_t r = 0; r < 5; r++) {
    Serial.flush();
    t0 = micros();
    for (uint8_t i = 0; i < 6; i++) Serial.print(F("#Temperature: 23.5 C\n")); // 126 bytes
    dt = micros() - t0;
    if (dt < best) best = dt;
  }
  Serial.flush();
  Serial.print(F("R,serial,print_126B_return,1,1,")); Serial.println(best);
}

char gpio_check[8] = "n/a";   // pin levels after each write: digitalWrite H/L, register H/L

void setup() {
  Serial.begin(115200);
  pinMode(TEST_PIN, OUTPUT);
#if !defined(__AVR__)
  // self-check: enable the input on the same pin and read the real level
  gpio_input_enable((gpio_num_t)TEST_PIN);
  digitalWrite(TEST_PIN, HIGH); gpio_check[0] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  digitalWrite(TEST_PIN, LOW);  gpio_check[1] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  FAST_SET();                   gpio_check[2] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  FAST_CLR();                   gpio_check[3] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  gpio_check[4] = 0;
#endif
  for (int i = 0; i < ARR_BYTES / 4; i++) buf32[i] = 0x01020304UL * (i + 1);
  delay(1500);
}

void loop() {
  Serial.println(F("BEGIN"));
  Serial.print(F("I,board,")); Serial.println(F(BOARD_NAME));
  Serial.print(F("I,F_CPU,")); Serial.println((uint32_t)F_CPU);
#if !defined(__AVR__)
  Serial.print(F("I,cpu_mhz,")); Serial.println(getCpuFrequencyMhz());
  Serial.print(F("I,core,")); Serial.println(ESP_ARDUINO_VERSION_STR);
#endif
  Serial.print(F("I,gpio_check,")); Serial.println(gpio_check);
  Serial.print(F("I,sizeof_int,"));    Serial.println(sizeof(int));
  Serial.print(F("I,sizeof_long,"));   Serial.println(sizeof(long));
  Serial.print(F("I,sizeof_double,")); Serial.println(sizeof(double));

  M("base", base_int, 1000);  M("base", base_flt, 1000);  M("base", base_loop, 1000);
  M("int", add_u8, 1000);  M("int", add_u16, 1000);  M("int", add_u32, 1000);
  M("int", mul_u8, 1000);  M("int", mul_u16, 1000);  M("int", mul_u32, 1000);
  M("int", div_u16, 1000); M("int", div_u32, 1000);
  M("int", add_int, 1000); M("int", mul_int, 1000);
  M("float", add_f, 1000); M("float", mul_f, 1000); M("float", div_f, 1000);
  M("float", sin_f, 1000); M("float", mul_d, 1000);
  M("gpio", dw, 1000);     M("gpio", dw_fast, 1000);
#if !defined(__AVR__)
  // dedicated GPIO takes the pin over (GPIO matrix), so it runs after the probes above
  static int pins[] = {TEST_PIN};
  dedic_gpio_bundle_config_t cfg = {};
  cfg.gpio_array = pins; cfg.array_size = 1; cfg.flags.out_en = 1;
  dedic_gpio_bundle_handle_t bundle;
  ESP_ERROR_CHECK(dedic_gpio_new_bundle(&cfg, &bundle));
  gpio_input_enable((gpio_num_t)TEST_PIN);
  char dchk[3];
  dedic_gpio_cpu_ll_write_mask(1, 1); dchk[0] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  dedic_gpio_cpu_ll_write_mask(1, 0); dchk[1] = '0' + gpio_get_level((gpio_num_t)TEST_PIN);
  dchk[2] = 0;
  Serial.print(F("I,gpio_check_dedic,")); Serial.println(dchk);
  M("gpio", dw_dedic, 1000);
#endif
  M("fmt", fmt_float, 10); M("fmt", fmt_long, 10);
  M("array", arr_sum_u8, ARR_BYTES); M("array", arr_sum_u32, ARR_BYTES);
  M("array", arr_memcpy, ARR_BYTES);
  serial_tests();
  Serial.println(F("END"));
  for (;;) delay(1000);
}
