0
0
Embedded Cprogramming~5 mins

Floating point cost on embedded systems in Embedded C

Choose your learning style9 modes available
Introduction

Floating point operations use more time and power on small devices. Knowing this helps write faster and efficient code.

When programming small devices like microcontrollers with limited power.
When you want your device to run longer on battery.
When you need your program to respond quickly without delays.
When you want to save memory and processing power.
When you decide between using whole numbers or decimals in calculations.
Syntax
Embedded C
float myNumber = 3.14f;
double myDouble = 3.14159;

Floating point numbers store decimal values like 3.14 or 2.718.

Using float uses less memory than double, but is less precise.

Examples
Use float for decimal numbers when less precision is okay.
Embedded C
float temperature = 36.5f;
// stores temperature with decimals
Use int for whole numbers to save time and power.
Embedded C
int count = 10;
// whole number, faster and cheaper to use
double gives more decimal places but costs more resources.
Embedded C
double preciseValue = 3.1415926535;
// more precise but slower on small devices
Sample Program

This program measures how long it takes to add numbers using floats versus ints. It shows floats usually take more time on embedded systems.

Embedded C
#include <stdio.h>
#include <time.h>

int main() {
    clock_t start, end;
    volatile float f = 0.0f;
    volatile int i = 0;
    int loops = 1000000;

    // Measure time for float addition
    start = clock();
    for (int j = 0; j < loops; j++) {
        f += 0.1f;
    }
    end = clock();
    double float_time = (double)(end - start) / CLOCKS_PER_SEC;

    // Measure time for int addition
    start = clock();
    for (int j = 0; j < loops; j++) {
        i += 1;
    }
    end = clock();
    double int_time = (double)(end - start) / CLOCKS_PER_SEC;

    printf("Float addition time: %f seconds\n", float_time);
    printf("Int addition time: %f seconds\n", int_time);

    return 0;
}
OutputSuccess
Important Notes

Floating point math can be much slower than integer math on small chips without special hardware.

Using integers or fixed-point math can save power and speed up your program.

Always test your program's speed if you use floating point on embedded devices.

Summary

Floating point operations cost more time and power on embedded systems.

Use integers when possible to make your program faster and more efficient.

Measure and test your code to choose the best number type for your needs.