如何使用python构建一个intarray,并将其与C语言一样高效?

2024-05-16 00:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

来自http://www.cs.bell-labs.com/cm/cs/pearls/sol01.html

C代码是这样的:

#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];

void set(int i) {        a[i>>SHIFT] |=  (1<<(i & MASK)); }
void clr(int i) {        a[i>>SHIFT] &= ~(1<<(i & MASK)); }
int  test(int i){ return a[i>>SHIFT] &   (1<<(i & MASK)); }

我找到了ctypesBitArraysnumpy,但我不确定它们是否能像上面的C代码那样高效。在

例如,如果我写这样的代码:

^{pr2}$

使用的空间是1M字节还是更多?在

有人知道一些好的库可以用Python做同样的事情吗?在


Tags: 代码comhttpshiftwwwcmmaskcs
3条回答

这个:

a=[c_int()]

生成一个包含对c\u int对象的引用的列表。在

乘以列表只会复制引用,因此:

^{pr2}$

实际上创建了一个包含1024*1024个引用的列表,该列表引用相同的单个cüint对象。在

如果需要1024*1024个c_int的数组,请执行以下操作:

a = c_int * (1024 * 1024)

您还可以检查内置的array模块:

>>> import array
>>> help(array)
Help on built-in module array:

NAME
    array

FILE
    (built-in)

DESCRIPTION
    This module defines an object type which can efficiently represent
    an array of basic values: characters, integers, floating point
    numbers.  Arrays are sequence types and behave very much like lists,
    except that the type of objects stored in them is constrained.  The
    type is specified at object creation time by using a type code, which
    is a single character.  The following type codes are defined:

        Type code   C Type             Minimum size in bytes 
        'b'         signed integer     1 
        'B'         unsigned integer   1 
        'u'         Unicode character  2 (see note) 
        'h'         signed integer     2 
        'H'         unsigned integer   2 
        'i'         signed integer     2 
        'I'         unsigned integer   2 
        'l'         signed integer     4 
        'L'         unsigned integer   4 
        'f'         floating point     4 
        'd'         floating point     8 

Numpy或ctypes都是不错的选择。但是你确定你的Python代码真的需要像C一样高效吗?你确定这段代码是性能热点吗?在

最好的做法是使用Python探查器来确保这段代码确实需要像C一样高效。如果确实如此,那么最简单的方法就是将代码保存在C中并使用ctypes或SWIG之类的东西链接到它。在

编辑:要回答更新后的问题,大小为N且元素大小为M的numpy数组将包含N*M字节的连续内存,外加一个标头和一些用于视图的字节。在

以下是一些相关链接:

相关问题 更多 >