写了段代码,分了40G,测了10次,没看出mmap和malloc有明显区别
# cat mmap.c
#include
#include
#include
#include
#include
int main(char ** argv)
{
size_t sz = 40000000000;
char * a = mmap(0, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
memset(a, 'a', sz);
printf("%.4s", &a[sz-5]);
}
# cat malloc.c
#include
#include
#include
int
main(int argc, char **argv)
{
size_t sz = 40000000000;
char *a = malloc(sz);
memset(a, 'a', sz);
printf("%.4s", &a[sz-5]);
return 0;
}
cc -o mmap.out mmap.c
cc -o malloc.out malloc.c
for i in {1..10}; do time ./mmap.out ; done 2>&1 | tee mmap.1
for i in {1..10}; do time ./malloc.out ; done 2>&1 | tee malloc.1
# cat mmap.1
aaaa
real 0m5.189s
user 0m2.017s
sys 0m3.175s
aaaa
real 0m5.302s
user 0m2.056s
sys 0m3.227s
aaaa
real 0m5.180s
user 0m2.014s
sys 0m3.168s
aaaa
real 0m5.288s
user 0m2.070s
sys 0m3.221s
aaaa
real 0m5.203s
user 0m2.053s
sys 0m3.152s
aaaa
real 0m5.184s
user 0m2.018s
sys 0m3.157s
aaaa
real 0m5.283s
user 0m2.122s
sys 0m3.164s
aaaa
real 0m5.204s
user 0m2.029s
sys 0m3.113s
aaaa
real 0m5.191s
user 0m2.090s
sys 0m3.104s
aaaa
real 0m5.277s
user 0m2.067s
sys 0m3.213s
# cat malloc.1
aaaa
real 0m5.093s
user 0m1.767s
sys 0m3.329s
aaaa
real 0m5.424s
user 0m2.119s
sys 0m3.270s
aaaa
real 0m5.311s
user 0m2.075s
sys 0m3.239s
aaaa
real 0m5.254s
user 0m2.086s
sys 0m3.170s
aaaa
real 0m5.226s
user 0m2.047s
sys 0m3.182s
aaaa
real 0m5.291s
user 0m2.100s
sys 0m3.193s
aaaa
real 0m5.193s
user 0m2.057s
sys 0m3.139s
aaaa
real 0m5.255s
user 0m2.033s
sys 0m3.224s
aaaa
real 0m5.251s
user 0m2.052s
sys 0m3.203s
aaaa
real 0m5.201s
user 0m2.027s
sys 0m3.177s
【 在 blitz 的大作中提到: 】
: 要分配一块4GBytes大小的内存,如果是
: 试了两种方法:
: 1. shm_open, ftruncate, mmap
: ...................