Yappi的使用

来源:互联网 发布:云计算服务器 翻译 编辑:程序博客网 时间:2024/06/05 14:25

最近要在项目里加入profiler,选择了yappi。

import yappiimport greenletimport functoolsimport reimport datetimeprofiler = Nonein_profile = Falseclass Profiler(object):    def __init__(self):        yappi.set_clock_type("cpu")        yappi.set_context_id_callback(lambda: id(greenlet.getcurrent()))        yappi.set_context_name_callback(            lambda: greenlet.getcurrent().__class__.__name__            )    def __call__(self, func):        @functools.wraps(func)        def wrapper(*args, **kwds):            try:                yappi.clear_stats()                yappi.start(builtins=True, profile_threads=False)                return func(*args, **kwds)            finally:                yappi.stop()                stats = yappi.convert2pstats(yappi.get_func_stats())                outFile = \                    '_'.join(re.split('-|:|\.| ', str(datetime.datetime.now())))                stats.dump_stats(                    '/tmp/profile_{}_{}'.format(func.__name__, outFile))                stats.sort_stats("cumulative")                stats.print_stats()                stats.sort_stats("tottime")                stats.print_stats()        return wrapperdef get_profiler():    global profiler    if profiler is None:        profiler = Profiler()    return profilerdef set_profile():    global in_profile    in_profile = Truedef is_in_profile():    return in_profile

在使用的可以使用get_profiler()这个函数来获得一个装饰器,把这个装饰器放到你要profile的函数上面,就可以对这个函数进行CPU耗时的profile啦。

这个装饰器在做profile的时候不光会在屏幕上打印一些profile的数据,还会以pstats的格式将这些profile写入/tmp/profile_xxx的一些文件中,注意,每个函数都是一个文件哦。你可以根据自己的需要来对这些功能进行取舍,或者改动出你自己的版本。

0 0