我正在 Google App Engine 中开发一个应用程序。我的方法之一是永不完成,这让我觉得它陷入了无限循环。我盯着它看,但想不通。
免责声明:我正在使用 http://code.google.com/p/gaeunit link text运行我的测试。也许它的行为很奇怪?
这是有问题的功能:
def _traverseForwards(course, c_levels):
''' Looks forwards in the dependency graph '''
result = {'nodes': [], 'arcs': []}
if c_levels == 0:
return result
model_arc_tails_with_course = set(_getListArcTailsWithCourse(course))
q_arc_heads = DependencyArcHead.all()
for model_arc_head in q_arc_heads:
for model_arc_tail in model_arc_tails_with_course:
if model_arc_tail.key() in model_arc_head.tails:
result['nodes'].append(model_arc_head.sink)
result['arcs'].append(_makeArc(course, model_arc_head.sink))
# rec_result = _traverseForwards(model_arc_head.sink, c_levels - 1)
# _extendResult(result, rec_result)
return result
本来以为可能是递归的错误,后来把递归注释掉了,问题依旧。如果使用 c_levels = 0
调用此函数,它运行良好。
它引用的模型:
class Course(db.Model):
dept_code = db.StringProperty()
number = db.IntegerProperty()
title = db.StringProperty()
raw_pre_reqs = db.StringProperty(multiline=True)
original_description = db.StringProperty()
def getPreReqs(self):
return pickle.loads(str(self.raw_pre_reqs))
def __repr__(self):
return "%s %s: %s" % (self.dept_code, self.number, self.title)
class DependencyArcTail(db.Model):
''' A list of courses that is a pre-req for something else '''
courses = db.ListProperty(db.Key)
def equals(self, arcTail):
for this_course in self.courses:
if not (this_course in arcTail.courses):
return False
for other_course in arcTail.courses:
if not (other_course in self.courses):
return False
return True
class DependencyArcHead(db.Model):
''' Maintains a course, and a list of tails with that course as their sink '''
sink = db.ReferenceProperty()
tails = db.ListProperty(db.Key)
它引用的实用函数:
def _makeArc(source, sink):
return {'source': source, 'sink': sink}
def _getListArcTailsWithCourse(course):
''' returns a LIST, not SET
there may be duplicate entries
'''
q_arc_heads = DependencyArcHead.all()
result = []
for arc_head in q_arc_heads:
for key_arc_tail in arc_head.tails:
model_arc_tail = db.get(key_arc_tail)
if course.key() in model_arc_tail.courses:
result.append(model_arc_tail)
return result
我是不是漏掉了一些很明显的东西,还是 GAEUnit 出了问题?
此外 - 导致此运行缓慢的测试在数据存储区中的任何类型的模型都不超过 5 个。我知道这可能很慢,但我的应用只执行一次,然后将其缓存。
最佳答案
忽略注释掉的递归,我不认为这应该是一个无限循环——你只是在有限的结果集上做一些 for 循环。
但是,看起来这确实真的很慢。您正在遍历整个表,然后在每个嵌套循环中执行更多数据存储查询。这种请求似乎不太可能在 GAE 上及时完成,除非您的表真的非常小。
一些粗略数字:
如果 H
= DepedencyArcHead
中的实体数量和 T
= average 每个 中的尾部数量>DependencyArcHead
然后:
_getListArcTailsWithCourse
正在做关于H*T
的查询(低估)。在“最坏”的情况下,从此函数返回的result
将包含H*T
元素。_traverseForwards
遍历所有这些结果H
次,因此执行另一个 H*(H*T) 次查询。- 即使
H
和T
只是 10 的数量级,您也可以进行 数千 查询。如果它们更大,那么...(如果您取消对递归调用的注释,这将忽略您将执行的任何其他查询)。
简而言之,我认为您可能希望尝试以稍微不同的方式组织您的数据。我会提出一个具体的建议,但我不清楚你到底想做什么。
关于Python:为什么这段代码会永远(无限循环?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986098/