memheap_tc.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. void * ptr_start;
  23. void *ptr[SLICE_NUM];
  24. int i, cnt = 0;
  25. /* init heap */
  26. ptr_start = 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, 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. rt_memheap_free(ptr[ptr_index]);
  55. ptr[ptr_index] = rt_memheap_alloc(&heap1, slice_size);
  56. }
  57. else /* realloc */
  58. {
  59. ptr[ptr_index] = rt_memheap_realloc(&heap1, ptr[ptr_index], slice_size);
  60. }
  61. }
  62. cnt ++;
  63. if (cnt % (TEST_TIMES / 10) == 0)
  64. {
  65. rt_kprintf(">");
  66. }
  67. }
  68. rt_kprintf("test OK!\n");
  69. /* test end */
  70. rt_memheap_detach(&heap1);
  71. rt_free_align((void *)ptr_start);
  72. }
  73. static rt_err_t utest_tc_init(void)
  74. {
  75. return RT_EOK;
  76. }
  77. static rt_err_t utest_tc_cleanup(void)
  78. {
  79. return RT_EOK;
  80. }
  81. static void testcase(void)
  82. {
  83. UTEST_UNIT_RUN(memheap_test);
  84. }
  85. UTEST_TC_EXPORT(testcase, "testcases.kernel.memheap_tc", utest_tc_init, utest_tc_cleanup, 10);