【问题标题】:Python's itertools product memory consumptionPython的itertools产品内存消耗
【发布时间】:2012-05-30 00:27:48
【问题描述】:

documentation 表示笛卡尔积函数

the actual implementation does not build up intermediate results in memory.

生成器怎么可能做到这一点?有人可以给我举个例子吗 2 个生成器的内存消耗有限?

【问题讨论】:

标签: python generator itertools


【解决方案1】:

查看模块的源代码,itertools.product() 实际上将每个参数转换为一个元组:

// product_new() in itertoolsmodule.c
for (i=0; i < nargs ; ++i) {
    PyObject *item = PyTuple_GET_ITEM(args, i);
    PyObject *pool = PySequence_Tuple(item); //<==== Call tuple(arg)
    if (pool == NULL)
        goto error;
    PyTuple_SET_ITEM(pools, i, pool);
    indices[i] = 0;
}

换句话说,itertools.product() 的内存消耗似乎与输入参数的大小成线性关系。

【讨论】:

    【解决方案2】:

    嗯,它还说:

    嵌套循环像里程表一样循环,最右边的元素 在每次迭代中推进。这种模式创建了一个字典 排序,以便如果输入的可迭代项已排序,则产品 元组按排序顺序发出。

    这几乎就是它在实现中的工作方式 (Modules/itertoolsmodule.c)

    这里是状​​态对象:

    typedef struct {
        PyObject_HEAD
        PyObject *pools;       /* tuple of pool tuples */
        Py_ssize_t *indices;   /* one index per pool */
        PyObject *result;      /* most recently returned result tuple */
        int stopped;           /* set to 1 when the product iterator is exhausted */
    } productobject;
    

    并且下一项由函数product_next返回,它使用这个状态和引用中描述的算法来生成下一个状态。请参阅this answer 以了解内存要求。

    对于普通教育,您可以阅读有关如何从 C 扩展 here 创建具有状态的生成器。

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多