分配时间对malloc函数所请求的内存的大小的依赖性
我编写了一个程序来计算为Malloc函数分配内存所需的时间。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
FILE *f;
f = fopen("malloc.txt","w");
int size = 1024*1024;
for (int i = 1; i <= 1024; i++) {
int *a;
clock_t begin = clock();
a = (int*)malloc(i*size);
clock_t end = clock();
free(a);
double time = (end - begin) / CLOCKS_PER_SEC;
fprintf(f,"%d %f\n",i, time);
}
fclose(f);
}
您能向我解释为什么该图形不会线性增加,而是勉强增加,而且突然有尖峰?
I wrote a program to calculate the time it takes to allocate memory for a malloc function.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
FILE *f;
f = fopen("malloc.txt","w");
int size = 1024*1024;
for (int i = 1; i <= 1024; i++) {
int *a;
clock_t begin = clock();
a = (int*)malloc(i*size);
clock_t end = clock();
free(a);
double time = (end - begin) / CLOCKS_PER_SEC;
fprintf(f,"%d %f\n",i, time);
}
fclose(f);
}
I then plot the allocation time dependency against the size of the memory to be allocated
can you explain to me why the graph is not increasing linearly but barely increasing and there are sudden spikes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在内部,
malloc()
可能会要求OS提供更大的内存,然后将其除以以进行后续分配。当malloc()
必须返回操作系统以获取更多内存时,可能是尖峰。因此,free()
不会将内存返回到操作系统,它只会将其返回到任何内部池malloc()
用于缓存内存的任何内部池。Internally,
malloc()
is likely asking the OS for a larger amount of memory, and then dividing it up for subsequent allocations. The spikes are likely whenmalloc()
has to go back to the OS to get more memory. Accordingly,free()
wouldn't return memory back to the OS, it would just return it back to whatever internal poolmalloc()
is using to cache memory.