美文网首页
python 性能跟踪的库封装

python 性能跟踪的库封装

作者: hugoren | 来源:发表于2018-03-28 17:21 被阅读0次

思路

python有各种的profile库来构建火焰图,查看程序运行的性能
1.常用的 time.time() - time.time()
2.imoprt cprofile
....
以上种种还要多写几行代码来达到目的
可以简单封装的,以装饰器方式,简便引用

封装

from colorama import *
from decorator import decorator

import cProfile
import inspect

from time import time as now


__all__ = ('cputime',  'docs', 'time', 'trace')


# CLI Color
init(autoreset=True)


@decorator
def cputime(f, *args, **kwargs):
    """Display CPU Time statistics of given function."""

    print(('CPU time for %s%s%s:' % (Fore.CYAN, _get_scope(f, args), Fore.RESET)))

    t = cProfile.Profile()
    r = t.runcall(f, *args, **kwargs)
    t.print_stats()

    return r


@decorator
def docs(f, *args, **kwargs):
    """Display Docstrings of given function."""

    print(('Documentation for %s%s%s:' % (Fore.CYAN, _get_scope(f, args), Fore.RESET)))
    print((inspect.getdoc(f)))

    return f(*args, **kwargs)


@decorator
def time(f, *args, **kwargs):
    """Display Runtime statistics of given function."""

    print(('Execution speed of %s%s%s:' % (Fore.CYAN, _get_scope(f, args), Fore.RESET)))
    _t0 = now()
    _r = f(*args, **kwargs)
    _t1 = now()

    total_time = _t1 - _t0
    print(('%s seconds' % (total_time)))

    return _r


@decorator
def trace(f, *args, **kwargs):
    """Display epic argument and context call information of given function."""

    _scope = _get_scope(f, args)

    print(("Calling %s%s%s with: \n   %sargs%s: %s \n   %skwargs%s: %s" % (
        Fore.CYAN, _scope, Fore.RESET, Fore.BLUE, Fore.RESET,
        args, Fore.BLUE, Fore.RESET, kwargs)))

    return f(*args, **kwargs)


def _get_scope(f, args):
    """Get scope nameo of given function."""

    _scope = inspect.getmodule(f).__name__
    # guess that function is a method of it's class
    try:
        if f.__name__ in dir(args[0].__class__):
            _scope += '.' + args[0].__class__.__name__
            _scope += '.' + f.__name__
        else:
            _scope += '.' + f.__name__
    except IndexError:
        _scope += '.' + f.__name__

    return _scope

引用

from show import time

@cputime
def test():
     print("i am boss")

test()
image.png

相关文章

网友评论

      本文标题:python 性能跟踪的库封装

      本文链接:https://www.haomeiwen.com/subject/bprucftx.html