Skip to content

Instantly share code, notes, and snippets.

@dreampuf

dreampuf/profiler.py

Created Sep 25, 2012
Embed
What would you like to do?
Python Profile script
#!/usr/bin/env python
# vim: fileencoding=utf-8
__author__ = "dreampuf<soddyque@gmail.com>"
import os
import sys
from functools import wraps
try:
from line_profiler import LineProfiler
except ImportError:
sys.stderr.write("`pip install line_profiler` first please\n")
try:
from memory_profiler import LineProfiler as MemeryProfiler
except ImportError:
sys.stderr.write("`pip install memory_profiler` first please\n")
try:
import objgraph
import tempfile
import subprocess
except ImportError:
sys.stderr.write("`pip install objgraph` first please\n")
lprofiler = LineProfiler()
def lpf(func):
"""Line Profiler function.
本装饰器函数将被装饰函数的执行耗时,以行为单位呈现
"""
profiled_func = lprofiler(func)
@wraps(func)
def inner(*args, **kws):
ret = profiled_func(*args, **kws)
profiled_func.print_stats()
return ret
return inner
mprofiler = MemeryProfiler()
def mpf(func):
"""Memery Profiler function.
本装饰器函数将被装饰函数的执行内存消耗,以行为单位呈现
"""
profiled_func = mprofiler(func)
@wraps(func)
def inner(*args, **kws):
ret = profiled_func(*args, **kws)
profiled_func.print_stats()
return ret
return inner
def picit(*args):
"""Piture it function.
将参数对象信息以图示的形式呈现。
"""
_, tmpf = tempfile.mkstemp(suffix='.png')
objgraph.show_refs(args, filename=tmpf)
if sys.platform.startswith('darwin'):
subprocess.call(('open', tmpf))
elif os.name == 'nt':
subprocess.call(('start', tmpf))
elif os.name == 'posix':
subprocess.call(('xdg-open', tmpf))
########## unittest ############
import unittest
class TestCase(unittest.TestCase):
def test_picit(self):
a = [i for i in xrange(100)]
b = xrange(100)
c = range(100)
picit(a, b, c)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment