![](/img/trans.png)
[英]How to use memory_profiler (python module) with class methods?
[英]How to use Profiler with Click CLI in Python
我有使用 Click 包来管理 CLI 的代码库。 有没有办法使用 cProfiler 来分析代码以进行优化?
import cProfile
import click
import io
def profile(fnc):
"""A decorator that uses cProfile to profile a function"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return retval
return inner
@click.group()
def cli1():
pass
@profile
@cli1.command()
@click.option('--zoom', '-z', type=int, default=1)
def fixed(zoom):
# Function goes here
cli = click.CommandCollection(sources=[cli1, default])
if __name__ == '__main__':
cli()
我需要在 Python 代码中分析fixed
函数。
我需要做同样的事情,在你的代码的帮助下,我想出了这个:
import click
@click.group()
@click.option("--profile", is_flag=True)
def main(profile: bool) -> None:
if profile:
import cProfile
import pstats
import io
import atexit
print("Profiling...")
pr = cProfile.Profile()
pr.enable()
def exit():
pr.disable()
print("Profiling completed")
s = io.StringIO()
pstats.Stats(pr, stream=s).sort_stats("cumulative").print_stats()
print(s.getvalue())
atexit.register(exit)
我的main
功能是您的cli1
功能。
然后你可以简单地将--profile
标志传递给你的 CLI,它会分析你想要的组的--profile
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.