为什么 numpy 数组有 96 字节的开销?

Eva*_*oll 6 python numpy internals python-3.x python-internals

如果我采用一个简单的空 numpy 数组,我可以看到它有 96 个字节的开销,

>>> sys.getsizeof( np.array([]) )
96
Run Code Online (Sandbox Code Playgroud)

那 96 个字节存储的是什么?这是在 numpy 或 Python 3 (cpython) 的 C 源代码中的哪里设置的?

Łuk*_*zyk 7

数组存在于numpy/core/include/numpy/ndarraytypes.h中的 C 源代码中

请参阅:https : //github.com/numpy/numpy/blob/master/numpy/core/include/numpy/ndarraytypes.h

看起来它有几个指针、维数和 PyObject_HEAD,它们的总数可能与您看到的字节数有关。

/*                                                                                                                                                                                                                                            
 * The main array object structure.                                                                                                                                                                                                           
 */
/* This struct will be moved to a private header in a future release */
typedef struct tagPyArrayObject_fields {
    PyObject_HEAD
    /* Pointer to the raw data buffer */
    char *data;
    /* The number of dimensions, also called 'ndim' */
    int nd;
    /* The size in each dimension, also called 'shape' */
    npy_intp *dimensions;
    /*                                                                                                                                                                                                                                        
     * Number of bytes to jump to get to the                                                                                                                                                                                                  
     * next element in each dimension                                                                                                                                                                                                         
     */
    npy_intp *strides;

    PyObject *base;
    /* Pointer to type structure */
    PyArray_Descr *descr;
    /* Flags describing array -- see below */
    int flags;
    /* For weak references */
    PyObject *weakreflist;
} PyArrayObject_fields;
Run Code Online (Sandbox Code Playgroud)

  • 我不明白你为什么这么说,@MikeRobinson - 内部结构可能与你无关,但这当然并不意味着它们实际上不相关。96 字节听起来可能不多,但有时,这就是性能好与差的区别。 (3认同)