malloc_test
Opened this issue · 0 comments
#include
#include <string.h>
#include <sys/time.h>
#define MAX_BUF_SIZE (102410)
#define MID_BUF_SIZE (10245)
#define MIN_BUF_SIZE (1024)
#define TI(tag)
struct timeval tv_begin_##tag;
struct timeval tv_end_##tag; \
do{ \
gettimeofday(&tv_begin_##tag, NULL);
}while(0)
#define TO(tag) do {
gettimeofday(&tv_end_##tag, NULL);
std::cout << #tag << " cost time:" << \
(tv_end_##tag.tv_sec -tv_begin_##tag.tv_sec)10001000 +
(tv_end_##tag.tv_usec - tv_begin_##tag.tv_usec) <<
"us" << std::endl;
}while(0)
int main(int, char**) {
TI(malloc_max_buf);
char *p = (char*)malloc(MAX_BUF_SIZE);
TO(malloc_max_buf);
TI(malloc_mid_buf);
char *q = (char*)malloc(MID_BUF_SIZE);
TO(malloc_mid_buf);
TI(malloc_min_buf);
char *j = (char*)malloc(MIN_BUF_SIZE);
TO(malloc_min_buf);
/// malloc 向系统申请内存,形成链表 p --> q --> j
/// free p 后,系统还无法收回
TI(free_max_buf);
free(p);
TO(free_max_buf);
/// 此时再malloc一块小于p指向的内存,相当于复用p指向那块
for (int i = 0; i < 100; ++i) {
TI(malloc_x1);
char *x1 = (char*)malloc(MID_BUF_SIZE);
TO(malloc_x1);
TI(free_x1);
free(x1);
TO(free_x1);
}
for (int i = 0; i < 100; ++i) {
TI(malloc_x2);
char *x2 = (char*)malloc(MIN_BUF_SIZE);
TO(malloc_x2);
TI(free_x2);
free(x2);
TO(free_x2);
}
return 0;
}