我给了这个答案,就同一主题类似的帖子:
这开始有点偏离主题(然后我就在你的问题扎),但发生的事情是类似于在Linux中分离进程时发生的情况。分叉时,有一种称为“拷贝写入”的机制,它只在内存写入时才复制新进程的内存空间。这样,如果分支进程exec立即执行一个新程序,那么您已经节省了复制原始程序内存的开销。
回到你的问题,这个想法是类似的。正如其他人指出的那样,请求内存立即获得虚拟内存空间,但实际页面只在写入时才分配。
这是什么目的?它基本上使mallocing内存的操作大致是一个大O(1)而不是Big O(n)操作(类似于Linux调度器扩展它的工作方式,而不是在一个大块中进行)。
为了证明我的意思,我做了以下实验:
[email protected]:~/test_code$ time ./bigmalloc
real 0m0.005s
user 0m0.000s
sys 0m0.004s
[email protected]:~/test_code$ time ./deadbeef
real 0m0.558s
user 0m0.000s
sys 0m0.492s
[email protected]:~/test_code$ time ./justwrites
real 0m0.006s
user 0m0.000s
sys 0m0.008s
的bigmalloc计划分配2000万个整数,但不与他们做任何事。 deadbeef向每个页面写入一个int,导致19531个写入,并且刚刚写入19531个int并将它们清零。正如你所看到的,deadbeef执行的时间比bigmalloc大100倍,比justwriter大50倍。
#include
int main(int argc, char **argv) {
int *big = malloc(sizeof(int)*20000000); // Allocate 80 million bytes
return 0;
}
。
#include
int main(int argc, char **argv) {
int *big = malloc(sizeof(int)*20000000); // Allocate 80 million bytes
// Immediately write to each page to simulate an all-at-once allocation
// assuming 4k page size on a 32-bit machine.
for (int* end = big + 20000000; big < end; big += 1024)
*big = 0xDEADBEEF;
return 0;
}
。
#include
int main(int argc, char **argv) {
int *big = calloc(sizeof(int), 19531); // Number of writes
return 0;
}