1 /*
2  * Copyright (c) 2021 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/timing/timing.h>
9 #include "utils.h"
10 
11 #define TEST_COUNT 100
12 #define TEST_SIZE 10
13 
heap_malloc_free(void)14 void heap_malloc_free(void)
15 {
16 	timing_t heap_malloc_start_time = 0U;
17 	timing_t heap_malloc_end_time = 0U;
18 
19 	timing_t heap_free_start_time = 0U;
20 	timing_t heap_free_end_time = 0U;
21 
22 	uint32_t count = 0U;
23 	uint32_t sum_malloc = 0U;
24 	uint32_t sum_free = 0U;
25 
26 	bool  failed = false;
27 	char  error_string[80];
28 	char  description[120];
29 	const char *notes = "";
30 
31 	timing_start();
32 
33 	while (count != TEST_COUNT) {
34 		heap_malloc_start_time = timing_counter_get();
35 		void *allocated_mem = k_malloc(TEST_SIZE);
36 
37 		heap_malloc_end_time = timing_counter_get();
38 		if (allocated_mem == NULL) {
39 			error_count++;
40 			snprintk(error_string, 78,
41 				  "alloc memory @ iteration %d", count);
42 			notes = error_string;
43 			break;
44 		}
45 
46 		heap_free_start_time = timing_counter_get();
47 		k_free(allocated_mem);
48 		heap_free_end_time = timing_counter_get();
49 
50 		sum_malloc += timing_cycles_get(&heap_malloc_start_time,
51 				&heap_malloc_end_time);
52 		sum_free += timing_cycles_get(&heap_free_start_time,
53 				&heap_free_end_time);
54 		count++;
55 	}
56 
57 	/*
58 	 * If count is 0, it means that there is not enough memory heap
59 	 * to do k_malloc at least once. Override the error string.
60 	 */
61 
62 	if (count == 0) {
63 		failed = true;
64 		notes = "Memory heap too small--increase it.";
65 	}
66 
67 	snprintf(description, sizeof(description),
68 		 "%-40s - Average time for heap malloc",
69 		 "heap.malloc.immediate");
70 	PRINT_STATS_AVG(description, sum_malloc, count, failed, notes);
71 
72 	snprintf(description, sizeof(description),
73 		 "%-40s - Average time for heap free",
74 		 "heap.free.immediate");
75 	PRINT_STATS_AVG(description, sum_free, count, failed, notes);
76 
77 	timing_stop();
78 }
79