Robert S. Ba..
10
我对同一主题的类似帖子给出了这个答案:
这开始有点偏离主题(然后我将它与你的问题联系起来),但是发生的事情类似于在Linux中分叉进程时发生的情况.在分叉时,有一种称为写入时复制的机制,它只在写入内存时复制新进程的内存空间.这样,如果分叉进程立即执行一个新程序,那么就节省了复制原始程序内存的开销.
回到你的问题,这个想法是类似的.正如其他人所指出的,请求内存会立即获得虚拟内存空间,但实际页面仅在写入时分配.
这是为了什么目的?它基本上使mallocing内存成为一个或多或少恒定的时间操作Big O(1)而不是Big O(n)操作(类似于Linux调度程序扩展它的工作方式而不是在一个大块中执行它).
为了证明我的意思,我做了以下实验:
rbarnes@rbarnes-desktop:~/test_code$ time ./bigmalloc
real 0m0.005s
user 0m0.000s
sys 0m0.004s
rbarnes@rbarnes-desktop:~/test_code$ time ./deadbeef
real 0m0.558s
user 0m0.000s
sys 0m0.492s
rbarnes@rbarnes-desktop:~/test_code$ time ./justwrites
real 0m0.006s
user 0m0.000s
sys 0m0.008s
bigmalloc程序分配了2000万个整数,但对它们没有任何作用.deadbeef在每个页面写入一个int,导致19531次写入,而justwrits分配19531个int并将它们归零.正如你所看到的,deadbeef执行的时间比bigmalloc长大约100倍,比justwrits长约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;
}