相关疑难解决方法(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万
查看次数

无法分配具有形状和数据类型的数组

我在Ubuntu 18上在numpy中分配大型数组时遇到了一个问题,而在MacOS上却没有遇到同样的问题。

我想一个numpy的阵列形状分配内存(156816, 36, 53806) 使用

np.zeros((156816, 36, 53806), dtype='uint8')
Run Code Online (Sandbox Code Playgroud)

当我在Ubuntu OS上遇到错误时

>>> import numpy as np
>>> np.zeros((156816, 36, 53806), dtype='uint8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
numpy.core._exceptions.MemoryError: Unable to allocate array with shape (156816, 36, 53806) and data type uint8
Run Code Online (Sandbox Code Playgroud)

我在MacOS上没有得到它:

>>> import numpy as np 
>>> np.zeros((156816, 36, 53806), dtype='uint8')
array([[[0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0], …
Run Code Online (Sandbox Code Playgroud)

python numpy data-science

21
推荐指数
5
解决办法
3万
查看次数

标签 统计

c ×1

data-science ×1

malloc ×1

numpy ×1

python ×1