行分析 python 代码 运行 作为后台服务

Line profiling python code running as background service

我知道使用 kerprof/profile/cProfile 分析独立脚本的方式。但是我如何将 python Web 应用程序 运行 配置为背景 service/long 运行 应用程序

经过深入研究和探索潜在的解决方案;我提出了以下解决方案:

  1. 在源文件中添加如下函数,并将原函数修饰为@do_cprofile

    import cProfile
    
    def do_cprofile(func):
        def profiled_func(*args, **kwargs):
            profile = cProfile.Profile()
            try:
                profile.enable()
                result = func(*args, **kwargs)
                profile.disable()
                return result
            finally:
                profile.dump_stats('/tmp/profile_bin.prof')
        return profiled_func
    
  2. 将生成的 /tmp/profile_bin.prof 转换为人类可读文件

    import pstats
    
    f = open('/tmp/human_readable_profile.prof', 'w')
    stats = pstats.Stats('/tmp/profile_bin.prof', stream=f)
    stats.sort_stats('cumulative').print_stats()
    f.close()