memheap_tc.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. #include <rtthread.h>
  11. #include <stdlib.h>
  12. #include "utest.h"
  13. #define HEAP_SIZE (64 * 1024)
  14. #define HEAP_ALIGN (4)
  15. #define SLICE_NUM (40)
  16. #define TEST_TIMES (100000)
  17. #define HEAP_NAME "heap1"
  18. #define SLICE_SIZE_MAX (HEAP_SIZE/SLICE_NUM)
  19. static void memheap_test(void)
  20. {
  21. struct rt_memheap heap1;
  22. rt_uint32_t ptr_start;
  23. void *ptr[SLICE_NUM];
  24. int i, cnt = 0;
  25. /* init heap */
  26. ptr_start = (rt_uint32_t)rt_malloc_align(HEAP_SIZE, HEAP_ALIGN);
  27. if (ptr_start == RT_NULL)
  28. {
  29. rt_kprintf("totle size too big,can not malloc memory!");
  30. return;
  31. }
  32. rt_memheap_init(&heap1, HEAP_NAME, (void *)ptr_start, HEAP_SIZE);
  33. /* test start */
  34. for (i = 0; i < SLICE_NUM; i++)
  35. {
  36. ptr[i] = 0;
  37. }
  38. /* test alloc */
  39. for (i = 0; i < SLICE_NUM; i++)
  40. {
  41. rt_uint32_t slice_size = rand() % SLICE_SIZE_MAX;
  42. ptr[i] = rt_memheap_alloc(&heap1, slice_size);
  43. }
  44. /* test realloc */
  45. while (cnt < TEST_TIMES)
  46. {
  47. rt_uint32_t slice_size = rand() % SLICE_SIZE_MAX;
  48. rt_uint32_t ptr_index = rand() % SLICE_NUM;
  49. rt_uint32_t operation = rand() % 2;
  50. if (ptr[ptr_index])
  51. {
  52. if (operation == 0) /* free and malloc */
  53. {
  54. if (ptr[ptr_index])
  55. {
  56. rt_memheap_free(ptr[ptr_index]);
  57. }
  58. ptr[ptr_index] = rt_memheap_alloc(&heap1, slice_size);
  59. }
  60. else /* realloc */
  61. {
  62. ptr[ptr_index] = rt_memheap_realloc(&heap1, ptr[ptr_index], slice_size);
  63. }
  64. }
  65. cnt ++;
  66. if (cnt % (TEST_TIMES / 10) == 0)
  67. {
  68. rt_kprintf(">");
  69. }
  70. }
  71. rt_kprintf("test OK!\n");
  72. /* test end */
  73. rt_memheap_detach(&heap1);
  74. rt_free_align((void *)ptr_start);
  75. }
  76. static rt_err_t utest_tc_init(void)
  77. {
  78. return RT_EOK;
  79. }
  80. static rt_err_t utest_tc_cleanup(void)
  81. {
  82. return RT_EOK;
  83. }
  84. static void testcase(void)
  85. {
  86. UTEST_UNIT_RUN(memheap_test);
  87. }
  88. UTEST_TC_EXPORT(testcase, "testcases.kernel.memheap_tc", utest_tc_init, utest_tc_cleanup, 10);