|
| 1 | + |
| 2 | +// nothing else than showing heap metric usage |
| 3 | +// released to public domain |
| 4 | + |
| 5 | +#include <ESP8266WiFi.h> |
| 6 | + |
| 7 | +void stats (const char* what) |
| 8 | +{ |
| 9 | + // we could use getFreeHeap() getMaxFreeBlockSize() and getHeapFragmentation() |
| 10 | + // or all at once: |
| 11 | + uint32_t free; |
| 12 | + uint16_t max; |
| 13 | + uint8_t frag; |
| 14 | + ESP.getHeapStats(&free, &max, &frag); |
| 15 | + |
| 16 | + Serial.printf("free: %5d - max: %5d - frag: %3d%% <- ", free, max, frag); |
| 17 | + // %s requires a malloc that could fail, using println instead: |
| 18 | + Serial.println(what); |
| 19 | +} |
| 20 | + |
| 21 | +void tryit (int blocksize) |
| 22 | +{ |
| 23 | + void** p; |
| 24 | + int blocks; |
| 25 | + |
| 26 | + // heap-used ~= blocks*sizeof(void*) + blocks*blocksize |
| 27 | + blocks = ((ESP.getMaxFreeBlockSize() / (blocksize + sizeof(void*))) + 3) & ~3; // rounded up, multiple of 4 |
| 28 | + |
| 29 | + Serial.printf("\nFilling memory with blocks of %d bytes each\n", blocksize); |
| 30 | + stats("before"); |
| 31 | + |
| 32 | + p = (void**)malloc(sizeof(void*) * blocks); |
| 33 | + for (int i = 0; i < blocks; i++) |
| 34 | + p[i] = malloc(blocksize); |
| 35 | + stats("array and blocks allocation"); |
| 36 | + |
| 37 | + for (int i = 0; i < blocks; i += 2) |
| 38 | + { |
| 39 | + if (p[i]) |
| 40 | + free(p[i]); |
| 41 | + p[i] = nullptr; |
| 42 | + } |
| 43 | + stats("freeing every other blocks"); |
| 44 | + |
| 45 | + for (int i = 0; i < blocks; i += 4) |
| 46 | + { |
| 47 | + if (p[i + 1]) |
| 48 | + free(p[i + 1]); |
| 49 | + p[i + 1] = nullptr; |
| 50 | + } |
| 51 | + stats("freeing every other remaining blocks"); |
| 52 | + |
| 53 | + for (int i = 0; i < blocks; i++) |
| 54 | + if (p[i]) |
| 55 | + free(p[i]); |
| 56 | + stats("freeing array"); |
| 57 | + |
| 58 | + free(p); |
| 59 | + stats("after"); |
| 60 | +} |
| 61 | + |
| 62 | +void setup() |
| 63 | +{ |
| 64 | + Serial.begin(115200); |
| 65 | + WiFi.mode(WIFI_OFF); |
| 66 | + |
| 67 | + tryit(8000); |
| 68 | + tryit(4000); |
| 69 | + tryit(2000); |
| 70 | + tryit(1000); |
| 71 | + tryit(500); |
| 72 | + tryit(200); |
| 73 | + tryit(100); |
| 74 | + tryit(50); |
| 75 | + tryit(15); |
| 76 | +} |
| 77 | + |
| 78 | +void loop () |
| 79 | +{ |
| 80 | +} |
0 commit comments