python - 在 Google App Engine 上分析/优化网站的最佳方式

标签 python google-app-engine

我目前正在尝试优化我的网站,该网站在 Google App Engine 上运行。这不是一件容易的事,因为我没有使用任何强大的工具。

有没有人有为此目的优化 Python 代码的经验? 你找到一个好的 Python 分析器了吗?

最佳答案

我找到了 Gprof2Dot非常有用。我尝试过的分析模块的输出非常不直观,无法解释。

Gprof2Dot 将 cProfile 输出变成一个漂亮的图表,最慢的链(?)突出显示,以及每个函数的一些信息(函数名称、花费在该函数上的时间百分比和调用次数)。

An example graph (1429x1896px)

我对 App Engine 做的不多,但是在分析非 Web 应用程序脚本时,我倾向于分析运行所有单元测试的脚本,这对现实世界的情况可能不是很准确

一个(更好的?)方法是使用一个脚本来执行伪造的 WSGI 请求,然后对其进行分析。

WSGI 是非常简单的协议(protocol),它基本上是一个带有两个参数的函数,一个带有请求信息,第二个带有回调函数(用于设置 header 等)。也许像下面这样(这是可能工作的伪代码)...

class IndexHandler(webapp.RequestHandler):
    """Your site"""
    def get(self):
        self.response.out.write("hi")

if __name__ == '__main__':
    application = webapp.WSGIApplication([
        ('.*', IndexHandler),
    ], debug=True)

    # Start fake-request/profiling bit
    urls = [
        "/",
        "/blog/view/hello",
        "/admin/post/edit/hello",
        "/makeanerror404",
        "/makeanerror500"
    ]

    def fake_wsgi_callback(response, headers):
        """Prints heads to stdout"""
        print("\n".join(["%s: %s" % (n, v) for n, v in headers]))
        print("\n")

    for request_url in urls:
        html = application({
        'REQUEST_METHOD': 'GET',
        'PATH_INFO': request_url},
        fake_wsgi_callback
        )
        print html

实际上,App Engine 文档解释了一种更好的分析应用程序的方法:

来自 http://code.google.com/appengine/kb/commontasks.html#profiling :

To profile your application's performance, first rename your application's main() function to real_main(). Then, add a new main function to your application, named profile_main() such as the one below:

def profile_main():
    # This is the main function for profiling 
    # We've renamed our original main() above to real_main()
    import cProfile, pstats
    prof = cProfile.Profile()
    prof = prof.runctx("real_main()", globals(), locals())
    print "<pre>"
    stats = pstats.Stats(prof)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(80)  # 80 = how many to print
    # The rest is optional.
    # stats.print_callees()
    # stats.print_callers()
    print "</pre>"

[...]

To enable the profiling with your application, set main = profile_main. To run your application as normal, simply set main = real_main.

关于python - 在 Google App Engine 上分析/优化网站的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/679670/

相关文章:

python - 使用 Python 从 Azure 服务总线主题检索消息属性

javascript - 使用长服务器端脚本加载网页的最佳实践

python - Populate() 不是可重入的 Django Google App Engine

python - 将列表中的单词与文件中的单词进行比较

python - 通过Python接口(interface)在Matlab中导入Tensorflow

Python 列出并对随机生成的数字进行排序

python - Google App Engine Python - 简单的 REST 处理程序

App Engine 上的 Laravel 8 : "Please provide a valid cache path"

python - 使用 Python 列表查询 Google App Engine 数据存储

python - AWS Glue Job Cloudformation - Cloudformation 中设置的值不固定