Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python构建一个int数组,并像C一样高效地使用它?_Python - Fatal编程技术网

如何使用python构建一个int数组,并像C一样高效地使用它?

如何使用python构建一个int数组,并像C一样高效地使用它?,python,Python,发件人: 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<

发件人:

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)); }
使用的空间是1M字节还是更多


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

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

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

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

以下是几个相关链接:


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

>>> 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 
这:

生成一个列表,其中包含对c_int对象的引用

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

a = [c_int()] * 1024 * 1024
实际上,创建了一个包含1024*1024个对同一个c_int对象的引用的列表

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

a = c_int * (1024 * 1024)

您认为当前实现效率不高的用例是什么?@Burnkhalid我为这个问题添加了更多的描述,
a=[c_int(9)]*1024*1024
使用超过
1M字节
?澄清一下:当您说“高效”是什么意思?你想最小化墙壁时间、最小化CPU时间、最小化内存使用还是其他什么?例如,DanielPryden主要用于内存使用,将
a=[c_int(9)]*1024*1024
使用超过
1M字节的
?你无论如何都不需要使用多个int,因为在Python中
int
可以(实际上)任意长度。
a = [c_int()] * 1024 * 1024
a = c_int * (1024 * 1024)