【问题标题】:Profiling an application that uses reactors/websockets and threads分析使用反应器/websockets 和线程的应用程序
【发布时间】:2015-08-02 06:15:29
【问题描述】:

您好,我编写了一个 Python 程序,该程序应该在无人值守的情况下运行。它的基本作用是通过几个线程中的 http get 请求获取一些数据,并通过 websockets 和高速公路框架获取数据。运行它 2 天表明它的内存需求不断增长,甚至在没有任何通知的情况下停止。 文档说我必须将反应堆作为应用程序中的最后一行代码运行。

我读到yappi 能够分析线程应用程序 这是一些伪代码

from autobahn.twisted.websocket import  WebSocketClientFactory,connectWS

if __name__ == "__main__":
#setting up a thread

#start the thread
Consumer.start()

xfactory = WebSocketClientFactory("wss://url")
cex_factory.protocol = socket
## SSL client context: default
##
if factory.isSecure:
    contextFactory = ssl.ClientContextFactory()
else:
    contextFactory = None

connectWS(xfactory, contextFactory)

reactor.run() 

yappi project site 的示例如下:

import yappi
def a(): 
    for i in range(10000000): pass

yappi.start()
a()
yappi.get_func_stats().print_all()
yappi.get_thread_stats().print_all()

所以我可以将yappi.start() 放在开头,yappi.get_func_stats().print_all() 加上yappi.get_thread_stats().print_all()reactor.run() 之后,但由于这段代码永远不会执行,所以我永远不会执行它。

那么我该如何分析这样的程序呢?

问候

【问题讨论】:

    标签: python autobahn yappi


    【解决方案1】:

    可以通过以下方式使用扭曲分析器:

    twistd -n --profile=profiling_results.txt --savestats --profiler=hotshot your_app
    

    hotshot 是一个默认的分析器,你也可以使用 cprofile。 或者您可以通过以下方式从您的 python 脚本运行 twistd:

    from twistd.scripts import run
    run()
    

    并通过sys.argv[1:1] = ["--profile=profiling_results.txt", ...]向脚本添加必要的参数 毕竟你可以通过以下方式将hotshot格式转换为calltree:

    hot2shot2calltree profiling_results.txt > calltree_profiling
    

    并打开生成的 calltree_profiling 文件:

    kcachegrind calltree_profiling
    

    有一个异步执行时间的剖析项目twisted-theseus 也可以试试pycharm的工具:thread concurrency

    这里有一个相关的问题sof 您还可以通过以下方式运行您的函数:

    reactor.callWhenRunning(your_function, *parameters_list)
    

    reactor.addSystemEventTrigger() 提供事件描述和您的分析函数调用。

    【讨论】:

      猜你喜欢
      • 2012-03-19
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      相关资源
      最近更新 更多