malloc分配不同大小内存的效率

分别对64B,1K, 4K, 16K, 256K, 4M, 64M,512M,2G大小进行测试,测试程序如下:

[source,c]
—-
#include
#include
#include
#include

long long count = 0;

void alarm_handler(int sig) {
printf(“%lld\n”, count);
count = 0;
alarm(1);
}

int main() {
signal(SIGALRM, alarm_handler);
alarm(1);

while(1) {
void *data = malloc(8589934592);
if (!data)
printf(“alloc error\n”);
free(data);
count++;
}
}
—-

机器配置:

内存:8GB,1600MHz

CPU:Intel Core I5,2 Core,4 Thread,2500MHz

测试时机器内存占用(足够各个大小):

[source,shell]
—-
blue@debian:/tmp$ free -g
total used free shared buff/cache available
Mem: 7 3 0 0 3 3
Swap: 7 0 7
—-

测试结果如下:

.每秒分配释放次数
|===
|大小 |次数

|while(1) count++;
|405343360

|64B
|39238565

|1K
|25090751

|4K
|25254046

|16K
|24580202

|256K
|28228175

|4M
|26599607

|64M
|200571

|512M
|166635

|2G
|134106
|===

3 Replies to “malloc分配不同大小内存的效率”

  1. 测试不准确,分配小块内存时,应该累计分配到一定量的内存时去看随着小块内存数量不断增多时花费时间的变化。

    1. malloc 分配不memset 是不是没有真正分配,那当malloc 2G 内存,只memset 2M ,那实际分配是2G 还是实际使用到多少才分配多少

      1. 你说的对,根据这个手册(https://linux.die.net/man/3/calloc)描述,其实只是在程序的堆上分配,只有具体访问的时候才会去做映射,但是calloc会做初始化,相当于malloc加memset。

回复 imliuda 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注