为什么 numpy.zeros 占用的空间很小 [英] Why does numpy.zeros takes up little space

查看:41
本文介绍了为什么 numpy.zeros 占用的空间很小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 numpy.zeros 占用这么小的空间?

I am wondering why numpy.zeros takes up such little space?

x = numpy.zeros(200000000)

这不占用内存,

x = numpy.repeat(0,200000000)

占用大约 1.5GB.numpy.zeros 是否创建了一个空指针数组?如果是这样,在 cython 中更改指针后,有没有办法将指针设置回数组中的空?如果我使用:

takes up around 1.5GB. Does numpy.zeros create an array of empty pointers? If so, is there a way to set the pointer back to empty in the array after changing it in cython? If I use:

x = numpy.zeros(200000000)
x[0:200000000] = 0.0

内存使用量上升.有没有办法改变一个值,然后把它改回python或cython中原来的numpy.zeros格式?

The memory usage goes way up. Is there a way to change a value, and then change it back to the format numpy.zeros originally had it in python or cython?

推荐答案

您使用的是 Linux 吗?Linux 具有延迟分配内存.numpy 中对 malloccalloc 的底层调用总是成功".在第一次访问内存之前,不会实际分配内存.

Are you using Linux? Linux has lazy allocation of memory. The underlying calls to malloc and calloc in numpy always 'succeed'. No memory is actually allocated until the memory is first accessed.

zeros 函数将使用 calloc 在第一次访问之前将任何分配的内存清零.因此,numpy 不需要显式地将数组清零,因此数组将被延迟初始化.而 repeat 函数不能依赖 calloc 来初始化数组.相反,它必须使用 malloc 然后将重复的复制到数组中的所有元素(从而强制立即分配).

The zeros function will use calloc which zeros any allocated memory before it is first accessed. Therfore, numpy need not explicitly zero the array and so the array will be lazily initialised. Whereas, the repeat function cannot rely on calloc to initialise the array. Instead it must use malloc and then copy the repeated to all elements in the array (thus forcing immediate allocation).

这篇关于为什么 numpy.zeros 占用的空间很小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆