awtk/tests/mem_test.cpp

81 lines
1.5 KiB
C++
Raw Normal View History

#undef HAS_STD_MALLOC
#include "base/mem.c"
#include <assert.h>
2018-02-21 19:36:38 +08:00
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
void check_zero(void* ptr, uint32_t size) {
uint32_t i = 0;
char* p = (char*)ptr;
for (i = 0; i < size; i++) {
assert(p[i] == 0);
}
}
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
tk_free(TKMEM_ALLOC(100));
2018-05-15 11:13:58 +08:00
2018-05-17 11:14:41 +08:00
for (i = 0; i < nr; i++) {
uint32_t size = rand() % 100;
void* ptr = TKMEM_CALLOC(size, 1);
2018-05-15 11:13:58 +08:00
check_zero(ptr, size);
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 {
TKMEM_FREE(ptr);
2018-05-15 11:13:58 +08:00
}
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);
tk_mem_dump();
2018-05-15 11:13:58 +08:00
2018-02-21 19:36:38 +08:00
return 0;
}