Google App Engine 代码优化

3 投票
4 回答
2593 浏览
提问于 2025-04-11 19:33

谷歌应用引擎告诉我需要优化这段代码。有没有人有什么建议可以帮我?

def index(request):
    user = users.get_current_user()
    return base.views.render('XXX.html', 
                 dict(profiles=Profile.gql("").fetch(limit=100), user=user))

然后在模板中我这样做:

{% for profile in profiles %}
  <a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
  <a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
  <br/>{{ profile.shortDisplay }}

使用的方法有:

def shortDisplay(self):
    return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)

def gravatarUrl(self):
    email = self.user.email().lower()
    default = "..."
    gravatar_url = "http://www.gravatar.com/avatar.php?"
    gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(), 
        'default':default, 'size':"64"})
    return gravatar_url

4 个回答

1

我遇到了一个问题,就是我的电脑处理器用了很多资源,但看起来工作量并不大。后来发现是因为有些查询被执行了多次。比如,在我的Django模板中,我先用post.comments.count来计算评论数量,然后又遍历了一遍post.comments。这就导致了两次执行:一次是计算数量,另一次是获取评论内容。哎呀,真是个失误!

我还想推荐你去看看Guido的Appstats工具。虽然它对Python的帮助不大,但它能很清楚地显示API调用花费的时间(还有它们之间的时间,这通常能告诉你哪里有Python代码运行得慢)。

你可以在这里获取这个库:https://sites.google.com/site/appengineappstats/

我在我的博客上写了一篇关于这个工具的文章(里面还有一些截图):http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats

Appstats http://blog.dantup.com/pi/appstats_4_thumb.png

3

我猜每次对每个项目都进行md5哈希计算是非常耗费资源的。更好的做法是把gravatar邮箱的哈希值存储起来。

6

高CPU使用率是因为每次请求都要获取100个实体。你可以考虑以下几种方法来改善这个问题:

  • 使用 Profile.all().fetch(100) 这样的方法会稍微快一点,而且更容易理解。
  • 从 Profile 模型中去掉一些不必要的属性。每个属性在反序列化实体时会消耗不少资源。
  • 每页显示的用户数量可以减少。
  • 把这个页面的输出存到内存缓存中,尽量从缓存中读取。这样,你就不需要频繁生成这个页面,即使CPU使用率高也没那么重要。

撰写回答