Instantly share code, notes, and snippets.

Last active October 31, 2023 09:52
Show Gist options
• Save cellularmitosis/506c878631f806cfe6f8c76d43b21c11 to your computer and use it in GitHub Desktop.
Arduino math timings (Pro Micro / ATMega32u4 5V 16MHz)

Blog 2022/10/18

# Arduino math timings (Pro Micro / ATMega32u4 5V 16MHz)

I threw together a quick series of Arduino sketches to measure the relative performance of the different math operations across different data types.

Measured by roughly filling up program space with e.g. 800 repeated calls, then dividing the number of calls by the elapsed time:

```#include <stdint.h>

void setup() {
Serial.begin(9600);
while (!Serial) { ; }
}

volatile float a = 1;
volatile float b = 2;
volatile float c = 3;

void loop() {
uint32_t then = micros();

c = a / b;
c = a / b;
c = a / b;
...
c = a / b;
c = a / b;
c = a / b;

uint32_t now = micros();
Serial.print(now - then);
Serial.print("\n");
delay(250);
}```

Results:

``````// Math timings (ops / ms):
//
//     uint8_t:   2212 / ms
//     uint16_t:  1117 / ms
//     uint32_t:   558 / ms
//     float:      127 / ms
//     double:     127 / ms (?!?)
//
//   multiplication + assignment:
//     uint8_t:   1562 / ms
//     uint16_t:   710 / ms
//     uint32_t:   151 / ms
//     float:       98 / ms
//     double:      98 / ms (?!?)
//
//   division + assignment:
//     uint8_t:    183 / ms
//     uint16_t:    75 / ms
//     uint32_t:    26 / ms
//     float:       34 / ms
//     double:      34 / ms (?!?)
``````

Apparently, `double` is actually only a `float` on this board. See also https://gcc.gnu.org/wiki/avr-gcc