【发布时间】:2011-08-05 12:19:54
【问题描述】:
我在 Python 中使用“附加”时遇到了一些性能问题。 我正在编写一个算法来检查一组(大)圆中是否有两个重叠的圆。 我首先将圆的极值点 (x_i-R_i & x_i+R_i) 放在一个列表中,然后对列表进行排序。
class Circle:
def __init__(self, middle, radius):
self.m = middle
self.r = radius
在这之间,我生成了 N 个随机圆圈并将它们放入“圆圈”列表中。
"""
Makes a list with all the extreme points of the circles.
Format = [Extreme, left/right ~ 0/1 extreme, index]
Seperate function for performance reason, python handles local variables faster.
Garbage collect is temporarily disabled since a bug in Python makes list.append run in O(n) time instead of O(1)
"""
def makeList():
"""gc.disable()"""
list = []
append = list.append
for circle in circles:
append([circle.m[0]-circle.r, 0, circles.index(circle)])
append([circle.m[0] + circle.r, 1, circles.index(circle)])
"""gc.enable()"""
return list
当运行 50k 圈时,生成列表需要 75 秒以上。正如你可能在我写的 cmets 中看到的那样,我禁用了垃圾收集,把它放在一个单独的函数中,使用
append = list.append
append(foo)
而不仅仅是
list.append(foo)
我禁用了 gc,因为经过一番搜索后,似乎 python 存在一个错误,导致 append 在 O(n) 而不是 O(c) 时间内运行。
那么这种方式是最快的方式还是有办法让它运行得更快? 非常感谢任何帮助。
【问题讨论】:
-
list在 python 中不是一个好的变量名。 -
list在任何语言中都不是一个好的变量名... -
"""String literals"""不是# comments。并且文档字符串必须在函数内部,而不是在函数之前。 -
@eumiro,CrazyJugglerDrummer:是的,改为 cirkeList。 @Sven:还不习惯 Python 的评论方式,我会记住你的建议。
标签: python performance append