samples: Basic system heap Demo

A demo to showcase some of the sys_heap functions

Signed-off-by: Jeppe Odgaard <jeppe.odgaard@prevas.dk>
This commit is contained in:
Jeppe Odgaard
2022-10-19 20:21:28 +02:00
committed by Stephanos Ioannidis
parent 010730aff6
commit 7d27309816
5 changed files with 112 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(sys_heap)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,41 @@
.. _system_heap:
System heap
###########
Overview
********
A simple sample that can be used with any :ref:`supported board <boards>` and
prints system heap usage to the console.
Building
********************
This application can be built on native_posix as follows:
.. zephyr-app-commands::
:zephyr-app: samples/basic/sys_heap
:host-os: unix
:board: native_posix
:goals: build
:compact:
To build for another board, change "native_posix" above to that board's name.
Running
*******
Run build/zephyr/zephyr.exe
Sample Output
*************
.. code-block:: console
System heap sample
allocated 0, free 196, max allocated 0, heap size 256
allocated 156, free 36, max allocated 156, heap size 256
allocated 100, free 92, max allocated 156, heap size 256
allocated 0, free 196, max allocated 156, heap size 256

View File

@@ -0,0 +1 @@
CONFIG_SYS_HEAP_RUNTIME_STATS=y

View File

@@ -0,0 +1,17 @@
sample:
description: System heap sample showing how to use sys_heap functions
name: Basic system heap sample
common:
integration_platforms:
- native_posix
harness: console
harness_config:
type: multi_line
ordered: true
regex:
- ".*allocated 15.,.*"
- ".*allocated 10.,.*"
- ".*allocated 0, free ..., max allocated ..., heap size 256.*"
tests:
sample.basic.sys_heap:
tags: heap statistics dynamic_memory

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2022 Jeppe Odgaard
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/sys/sys_heap.h>
#define HEAP_SIZE 256
static char heap_mem[HEAP_SIZE];
static struct sys_heap heap;
void print_sys_memory_stats(void);
void main(void)
{
void *p;
printk("System heap sample\n\n");
sys_heap_init(&heap, heap_mem, HEAP_SIZE);
print_sys_memory_stats();
p = sys_heap_alloc(&heap, 150);
print_sys_memory_stats();
p = sys_heap_realloc(&heap, p, 100);
print_sys_memory_stats();
sys_heap_free(&heap, p);
print_sys_memory_stats();
}
void print_sys_memory_stats(void)
{
struct sys_memory_stats stats;
sys_heap_runtime_stats_get(&heap, &stats);
printk("allocated %zu, free %zu, max allocated %zu, heap size %u\n",
stats.allocated_bytes, stats.free_bytes,
stats.max_allocated_bytes, HEAP_SIZE);
}