相关疑难解决方法(0)

为什么malloc + memset比calloc慢?

众所周知,它与初始化分配的内存calloc不同malloc.使用时calloc,内存设置为零.使用时malloc,内存不会被清除.

所以在日常工作中,我认为callocmalloc+ memset.顺便说一下,为了好玩,我为基准编写了以下代码.

结果令人困惑.

代码1:

#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
        int i=0;
        char *buf[10];
        while(i<10)
        {
                buf[i] = (char*)calloc(1,BLOCK_SIZE);
                i++;
        }
}
Run Code Online (Sandbox Code Playgroud)

代码1的输出:

time ./a.out  
**real 0m0.287s**  
user 0m0.095s  
sys 0m0.192s  
Run Code Online (Sandbox Code Playgroud)

代码2:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
        int i=0;
        char *buf[10];
        while(i<10)
        {
                buf[i] = (char*)malloc(BLOCK_SIZE);
                memset(buf[i],'\0',BLOCK_SIZE);
                i++;
        }
}
Run Code Online (Sandbox Code Playgroud)

代码2的输出:

time ./a.out   
**real 0m2.693s**  
user 0m0.973s  
sys 0m1.721s  
Run Code Online (Sandbox Code Playgroud)

更换 …

c malloc

249
推荐指数
2
解决办法
5万
查看次数

标签 统计

c ×1

malloc ×1