awtk/tests/mem_test.cpp

77 lines
1.4 KiB
C++
Raw Normal View History

2018-05-10 13:47:39 +08:00
#include "base/mem.h"
#include <assert.h>
2018-02-21 19:36:38 +08:00
2018-05-15 11:20:34 +08:00
#ifndef HAS_STD_MALLOC
2018-05-15 11:13:58 +08:00
#define STACK_SIZE 1000
uint32_t s_heap_mem[1024 * 100];
typedef struct _mem_stack_t {
void* ptr[1000];
uint32_t top;
uint32_t max;
2018-05-17 11:14:41 +08:00
} mem_stack_t;
2018-05-15 11:13:58 +08:00
void mem_stack_init(mem_stack_t* s) {
memset(s, 0x00, sizeof(mem_stack_t));
s->max = ARRAY_SIZE(s->ptr);
}
void mem_stack_push(mem_stack_t* s, void* ptr) {
assert(s->top < s->max);
s->ptr[s->top++] = ptr;
}
2018-06-03 10:19:34 +08:00
bool_t mem_stack_has_space(mem_stack_t* s) {
return s->top < s->max;
}
2018-05-15 11:13:58 +08:00
void* mem_stack_pop(mem_stack_t* s) {
assert(s->top > 0);
s->top--;
return s->ptr[s->top];
}
void mem_stack_free_n(mem_stack_t* s, uint32_t nr) {
2018-05-17 11:14:41 +08:00
for (uint32_t i = 0; i < nr && s->top > 0; i++) {
tk_free(mem_stack_pop(s));
2018-05-15 11:13:58 +08:00
}
}
2018-02-21 19:36:38 +08:00
int main() {
2018-05-15 11:13:58 +08:00
mem_stack_t s;
2018-02-21 19:36:38 +08:00
uint32_t i = 0;
2018-05-17 11:14:41 +08:00
uint32_t nr = 10000 * 10000;
2018-05-15 11:13:58 +08:00
srand(time(0));
mem_stack_init(&s);
2018-05-24 11:18:46 +08:00
tk_mem_init(s_heap_mem, sizeof(s_heap_mem));
2018-02-21 19:36:38 +08:00
2018-05-15 11:13:58 +08:00
tk_free(tk_alloc(100));
2018-05-17 11:14:41 +08:00
for (i = 0; i < nr; i++) {
uint32_t size = rand() % 100;
2018-05-15 11:13:58 +08:00
void* ptr = tk_calloc(size, 1);
2018-05-17 11:14:41 +08:00
if (ptr != NULL) {
if (mem_stack_has_space(&s)) {
2018-05-15 11:13:58 +08:00
mem_stack_push(&s, ptr);
} else {
tk_free(ptr);
}
2018-02-21 19:36:38 +08:00
} else {
2018-05-15 11:13:58 +08:00
mem_stack_free_n(&s, s.top >> 1);
2018-02-21 19:36:38 +08:00
}
}
2018-05-15 11:13:58 +08:00
mem_stack_free_n(&s, s.top);
2018-05-24 11:18:46 +08:00
tk_mem_info_dump();
2018-05-15 11:13:58 +08:00
2018-02-21 19:36:38 +08:00
return 0;
}
2018-05-15 11:20:34 +08:00
#else
int main() {
printf("HAS_STD_MALLOC defined, no test.\n");
return 0;
}
#endif