最近要在项目里加入profiler,选择了yappi。
import yappi
import greenlet
import functools
import re
import datetime
profiler = None
in_profile = False
class 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 wrapper
def get_profiler():
global profiler
if profiler is None:
profiler = Profiler()
return profiler
def set_profile():
global in_profile
in_profile = True
def is_in_profile():
return in_profile
在使用的可以使用get_profiler()
这个函数来获得一个装饰器,把这个装饰器放到你要profile的函数上面,就可以对这个函数进行CPU耗时的profile啦。
这个装饰器在做profile的时候不光会在屏幕上打印一些profile的数据,还会以pstats的格式将这些profile写入/tmp/profile_xxx的一些文件中,注意,每个函数都是一个文件哦。你可以根据自己的需要来对这些功能进行取舍,或者改动出你自己的版本。