测试系统:
系统:uname -a
Linux debian 2.6.32-5-amd64 #1 SMP Mon Jan 16 16:22:28 UTC 2012 x86_64 GNU/Linux
cpu: cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c
2 Intel(R) Core(TM)2 Duo CPU P8700 @ 2.53GHz
mem:cat /proc/meminfo
MemTotal: 4030064 kB
MemFree: 1713340 kB
Buffers: 77660 kB
Cached: 629620 kB
SwapCached: 0 kB
想在自己的应用中实现mempool ,以测试的结果来看,实现的必要性不是太大;
malloc 1000 * 10000 ,用时 25 s
malloc 100 * 10000 ,用时 2 s
更多的测试,有兴趣的朋友可以试试。
测试结果:
测试1: 每次申请 1000个内存块,大小随机,
int mem_pool[] = {1024, 2048, 4096, 8192,
10240, 20480, 40960, 81920,
102400, 204800, 409600, 819200,
1024000}
const int const malloc_count = 1000;
gcc -g -o testmalloc memmalloc.c && ./testmalloc
malloc 1000 * 10000 ,用时 25 s
测试2:每次申请 100个内存块,大小随机,
int mem_pool[] = {1024, 2048, 4096, 8192,
10240, 20480, 40960, 81920,
102400, 204800, 409600, 819200,
1024000}
const int const malloc_count = 100;
gcc -g -o testmalloc memmalloc.c && ./testmalloc
malloc 100 * 10000 ,用时 2 s
测试代码如下:
#include <stdlib.h>
#include <malloc.h>
#include <sys/time.h>
int main(){
const int const count =10000;
const int const malloc_count = 1000;
int mem_pool[] = {1024, 2048, 4096, 8192,
10240, 20480, 40960, 81920,
102400, 204800, 409600, 819200,
1024000};
int i, j;
const int const mem_pool_count = 13;
int *p_data[malloc_count];
struct timeval tv, tv2;
struct timezone tz, tz2;
gettimeofday (&tv , &tz);
for (i = 0; i < count; ++i){
for (j = 0; j < malloc_count; ++j){
p_data[j] = (int *) malloc(mem_pool[rand() % mem_pool_count]);
}
for (j = 0; j < malloc_count; ++j){
free(p_data[j]);
}
}
gettimeofday (&tv2 , &tz2);
printf("malloc %d * %d ,用时 %u s\n", malloc_count, count, tv2.tv_sec - tv.tv_sec);
}