Pugz
Pugz

Reputation: 1029

Most memory-efficient way to define hundreds of double constants

What is the most memory-efficient way to define hundreds of double (64-bit floating point) constants for use in an embedded C program? Please note this application is memory-constrained and I need to save as much RAM as possible.

It's an Atmel AVR with 2048B RAM clocked @ 8MHz. 32K Flash.

Upvotes: 3

Views: 188

Answers (3)

jeb
jeb

Reputation: 82317

Expecting you use the AVRStudio:
When you want to place variables to flash only, you could use

#include <avr/pgmspace.h>
const char myString[] PROGMEM = "AT\r";
const float myFloat PROGMEM = 3.1415926535f;

Some more infos about placing and reading (for AVR) can be found at Data in Program Space

There doesn't exists a general solution, it depends on the platform(von Neumann or Harvard) and toolchain.

Some compilers uses
__attribute__(section(".myFlashSection"))
some others uses pragmas like
#pragma SET_CONST_PAGE(ConstArea).

And there are some strange ones like

#pragma define_section flash_table ".myFlashTable.text" RW
#pragma section flash_table begin

And others moves always the const data to a flash section.

Upvotes: 2

Felipe Lavratti
Felipe Lavratti

Reputation: 2967

Declare it as const double array_name[] = { ... }; and expect the linker to store it on flash only.

Be aware you must check the map file to be sure no copy has been made to the ram.

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222933

In large part, the way to have constants not use memory is to store them in a file and read them as needed.

If you cannot do that, then the constants must form part of the program, and they will occupy memory one way or another, either in a data segment or as immediates in instructions.

If full precision is not needed, you may be able to reduce the data to float instead of double.

A few processor architectures provide for encoding simple floating-point constants in instructions. If you are targeting such a processor, you should study its documentation to learn what constants are supported. This is unlikely to be useful for general data.

If the data has some pattern, you may be able to use that to generate parts as needed as run-time. (This includes various forms of compression and decompression, which depend on patterns in data.) Obviously, this depends on the nature of the data, which you have not included in your question.

Another possibility that should be considered is whether your program needs all the raw data it uses or whether some portion of the work can be performed in advance to reduce the data needed.

Otherwise, by and large, data is data, and it takes the space it takes.

Upvotes: 2

Related Questions