【发布时间】:2014-10-30 02:36:33
【问题描述】:
使用 cProfile:
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 17.834 17.834 <string>:1(<module>)
1 0.007 0.007 17.834 17.834 basher.py:5551(_refresh)
1 0.000 0.000 10.522 10.522 basher.py:1826(RefreshUI)
4 0.024 0.006 10.517 2.629 basher.py:961(PopulateItems)
211 1.494 0.007 7.488 0.035 basher.py:1849(PopulateItem)
231 0.074 0.000 6.734 0.029 {method 'sort' of 'list' objects}
215 0.002 0.000 6.688 0.031 bosh.py:4764(getOrdered)
1910 3.039 0.002 6.648 0.003 bosh.py:4770(<lambda>)
253 0.178 0.001 5.600 0.022 bosh.py:3325(getStatus)
1 0.000 0.000 5.508 5.508 bosh.py:4327(refresh)
1911 3.051 0.002 3.330 0.002 {method 'index' of 'list' objects}
1910 3.039 0.002 6.648 0.003 bosh.py:4770(<lambda>) 行让我很困惑。在 bosh.py:4770 我有 modNames.sort(key=lambda a: (a in data) and data.index(a)),数据和 modNames 是列表。注意1911 3.051 0.002 3.330 0.002 {method 'index' of 'list' objects},它似乎来自这条线。
那么为什么这么慢呢?有什么办法可以重写这个sort(),让它运行得更快?
编辑:我缺少了解这个 lambda 的最后一种成分:
>>> True and 3
3
【问题讨论】:
-
函数体是
a in data and data.index(a),其中的两个操作是O(n),其中n是数据的列表大小。如果不回答你的整个问题,我会把责任归咎于这个 lambda 函数。每次调用时,lambda 都会扫描data。如果你对data使用字典而不是列表,它可能会更快,因为字典的平均查找时间复杂度为 O(1)。
标签: python python-2.7 lambda cprofile