len()Python内置函数的功能成本是多少?(列表/元组/串/字典)
在分析我的Python应用程序时,我发现len()使用集合时似乎非常昂贵.请参阅以下代码:
import cProfile
def lenA(s):
for i in range(1000000):
len(s);
def lenB(s):
for i in range(1000000):
s.__len__();
def main():
s = set();
lenA(s);
lenB(s);
if __name__ == "__main__":
cProfile.run("main()","stats");
Run Code Online (Sandbox Code Playgroud)
根据profiler的统计数据,lenA()似乎比lenB()以下慢14倍:
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.986 1.986 3.830 3.830 .../lentest.py:5(lenA)
1000000 1.845 0.000 1.845 0.000 {built-in method len}
1 0.273 0.273 0.273 0.273 .../lentest.py:9(lenB)
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?目前我使用__len__()而不是len(),但代码看起来很脏:(
当我遇到len函数的C实现时,我正在阅读有关python内置函数的实现的信息。
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
Run Code Online (Sandbox Code Playgroud)
我无法理解这段代码中发生了什么。我不知道C是如何工作的。有人可以解释这段代码在做什么吗?
我从https://github.com/python/cpython/blob/master/Python/bltinmodule.c获取了代码
编辑:我只是很好奇len函数是如此之快,在这段代码中绊倒了。我只想知道为什么使用函数PyObject_Size检查对象的大小为零,然后使用PyLong_FromSsize_t返回实际大小。
python ×4
algorithm ×1
arrays ×1
c ×1
collections ×1
cpython ×1
methods ×1
performance ×1
profiling ×1
set ×1