|
| 1 | +/* |
| 2 | + * Copyright (c) 2006-2019, RT-Thread Development Team |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + * |
| 6 | + * Change Logs: |
| 7 | + * Date Author Notes |
| 8 | + * 2019-01-16 flybreak the first version |
| 9 | + */ |
| 10 | + |
| 11 | +#include <rtthread.h> |
| 12 | +#include <stdlib.h> |
| 13 | +#include "utest.h" |
| 14 | + |
| 15 | +#define HEAP_SIZE (64 * 1024) |
| 16 | +#define HEAP_ALIGN (4) |
| 17 | +#define SLICE_NUM (40) |
| 18 | +#define TEST_TIMES (100000) |
| 19 | +#define HEAP_NAME "heap1" |
| 20 | +#define SLICE_SIZE_MAX (HEAP_SIZE/SLICE_NUM) |
| 21 | + |
| 22 | +static void memheap_test(void) |
| 23 | +{ |
| 24 | + struct rt_memheap heap1; |
| 25 | + rt_uint32_t ptr_start; |
| 26 | + void *ptr[SLICE_NUM]; |
| 27 | + int i, cnt = 0; |
| 28 | + |
| 29 | + /* init heap */ |
| 30 | + ptr_start = (rt_uint32_t)rt_malloc_align(HEAP_SIZE, HEAP_ALIGN); |
| 31 | + if (ptr_start == RT_NULL) |
| 32 | + { |
| 33 | + rt_kprintf("totle size too big,can not malloc memory!"); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + rt_memheap_init(&heap1, HEAP_NAME, (void *)ptr_start, HEAP_SIZE); |
| 38 | + |
| 39 | + /* test start */ |
| 40 | + for (i = 0; i < SLICE_NUM; i++) |
| 41 | + { |
| 42 | + ptr[i] = 0; |
| 43 | + } |
| 44 | + /* test alloc */ |
| 45 | + for (i = 0; i < SLICE_NUM; i++) |
| 46 | + { |
| 47 | + rt_uint32_t slice_size = rand() % SLICE_SIZE_MAX; |
| 48 | + ptr[i] = rt_memheap_alloc(&heap1, slice_size); |
| 49 | + } |
| 50 | + /* test realloc */ |
| 51 | + while (cnt < TEST_TIMES) |
| 52 | + { |
| 53 | + rt_uint32_t slice_size = rand() % SLICE_SIZE_MAX; |
| 54 | + rt_uint32_t ptr_index = rand() % SLICE_NUM; |
| 55 | + rt_uint32_t operation = rand() % 2; |
| 56 | + |
| 57 | + if (ptr[ptr_index]) |
| 58 | + { |
| 59 | + if (operation == 0) /* free and malloc */ |
| 60 | + { |
| 61 | + if (ptr[ptr_index]) |
| 62 | + { |
| 63 | + rt_memheap_free(ptr[ptr_index]); |
| 64 | + } |
| 65 | + ptr[ptr_index] = rt_memheap_alloc(&heap1, slice_size); |
| 66 | + } |
| 67 | + else /* realloc */ |
| 68 | + { |
| 69 | + ptr[ptr_index] = rt_memheap_realloc(&heap1, ptr[ptr_index], slice_size); |
| 70 | + } |
| 71 | + } |
| 72 | + cnt ++; |
| 73 | + if (cnt % (TEST_TIMES / 10) == 0) |
| 74 | + { |
| 75 | + rt_kprintf(">"); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + rt_kprintf("test OK!\n"); |
| 80 | + |
| 81 | + /* test end */ |
| 82 | + rt_memheap_detach(&heap1); |
| 83 | + rt_free_align((void *)ptr_start); |
| 84 | +} |
| 85 | + |
| 86 | +static rt_err_t utest_tc_init(void) |
| 87 | +{ |
| 88 | + return RT_EOK; |
| 89 | +} |
| 90 | + |
| 91 | +static rt_err_t utest_tc_cleanup(void) |
| 92 | +{ |
| 93 | + return RT_EOK; |
| 94 | +} |
| 95 | + |
| 96 | +static void testcase(void) |
| 97 | +{ |
| 98 | + UTEST_UNIT_RUN(memheap_test); |
| 99 | +} |
| 100 | +UTEST_TC_EXPORT(testcase, "testcases.kernel.memheap_tc", utest_tc_init, utest_tc_cleanup, 10); |
0 commit comments