finds size of largest block of heap memory

Dependents:   myBlueUSB mbed_TANK_Kinect myBlueUSB_ros myBlueUSB_localfix

Files at this revision

API Documentation at this revision

Comitter:
networker
Date:
Wed May 04 09:14:02 2011 +0000
Commit message:

Changed in this revision

AvailableMemory.cpp Show annotated file Show diff for this revision Revisions of this file
AvailableMemory.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 2b2aa11cebd7 AvailableMemory.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/AvailableMemory.cpp	Wed May 04 09:14:02 2011 +0000
@@ -0,0 +1,34 @@
+#include "AvailableMemory.h"
+#include <stdlib.h>
+
+namespace segundo {
+namespace Utilities {
+
+int AvailableMemory(int resolution, int maximum, bool disableInterrupts) {
+
+    if (resolution < 1) resolution = 1;
+    if (maximum < 0) maximum = 0;
+
+    int low = 0;
+    int high = maximum + 1;
+
+    if (disableInterrupts) __disable_irq();
+
+    while (high - low > resolution) {
+        int mid = (low + high) / 2;
+        void* p = malloc(mid);
+        if (p == NULL) {
+            high = mid;
+        } else {
+            free(p);
+            low = mid;
+        }
+    }
+
+    if (disableInterrupts) __enable_irq();
+
+    return low;
+}
+
+} // namespace Utilities
+} // namespace segundo
\ No newline at end of file
diff -r 000000000000 -r 2b2aa11cebd7 AvailableMemory.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/AvailableMemory.h	Wed May 04 09:14:02 2011 +0000
@@ -0,0 +1,46 @@
+/** @file
+ * Return the memory available for a malloc call.
+ */
+#ifndef SEGUNDO_UTILITIES_AVAILABLEMEMORY_H
+#define SEGUNDO_UTILITIES_AVAILABLEMEMORY_H
+
+/**
+ * Segundo Equipo
+ */
+namespace segundo {
+/**
+ * A collection of utilities
+ */
+namespace Utilities {
+
+/** Return the memory available for a malloc call.
+ * This is done by a binary search approach
+ * calling malloc/free starting with a maximum.
+ *
+ * Example:
+ * @code
+ * #include <stdio.h>
+ * #include "AvailableMemory.h"
+ *
+ * int main() {
+ *
+ *     printf("Available memory (bytes to nearest 256) : %d\n", AvailableMemory());
+ *     printf("Available memory (exact bytes) : %d\n", AvailableMemory(1));
+ *
+ * }
+ * @endcode
+ * @param resolution Resolution in number of bytes,
+ * 1 will return the exact value,
+ * default will return the available memory to the nearest 256 bytes
+ * @param maximum Maximum amount of memory to check, default is 32K (0x8000)
+ * @param disableInterrupts Disable interrupts whilst checking, default is true
+ * @return Available memory in bytes accurate to within resolution
+ */
+int AvailableMemory(int resolution = 256, int maximum = 0x8000, bool disableInterrupts = true);
+
+} // namespace Utilities
+} // namespace segundo
+
+using namespace segundo::Utilities;
+
+#endif // SEGUNDO_UTILITIES_AVAILABLEMEMORY_H
\ No newline at end of file