Yappi的使用
2015-09-23 17:10
711 查看
最近要在项目里加入profiler,选择了yappi。
在使用的可以使用
这个装饰器在做profile的时候不光会在屏幕上打印一些profile的数据,还会以pstats的格式将这些profile写入/tmp/profile_xxx的一些文件中,注意,每个函数都是一个文件哦。你可以根据自己的需要来对这些功能进行取舍,或者改动出你自己的版本。
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的一些文件中,注意,每个函数都是一个文件哦。你可以根据自己的需要来对这些功能进行取舍,或者改动出你自己的版本。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法