파이썬 API 둘러보기

myprofile(custom)

연습 삼아 작성해봄.

 

사용 예시:

import myprofile


@myprofile.profile
def count1(n: int):
    cnt = 0
    for n in range(n):
        cnt += 1

    return cnt


@myprofile.Runtime(prec=6)
def count2(n: int):
    cnt = 0
    for n in range(n):
        cnt += 1

    return cnt


n = 10000000
print(count1(n))
print('-'*40)
print(count2(n))

결과:

         2 function calls in 0.816 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.816    0.816    0.816    0.816 HelloPython.py:4(count1)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


10000000
----------------------------------------
elapsed time: 0.800231 seconds
10000000

 

myprofile.py

@Runtime 은 단순히 실행 시간을 출력한다(prec=정밀도).

@profile 은 cProfile.run()과 같다.

메인으로 실행하면 파일 이름을 입력받아서 역시 cProfile을 사용한다.

"""
myprofile.py
by jhjang

references:
    http://schoolofweb.net/blog/posts/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0-decorator/
    http://scottlobdell.me/2015/04/decorators-arguments-python/
    https://stackoverflow.com/questions/5375624/a-decorator-that-profiles-a-method-call-and-logs-the-profiling-result
"""

from functools import wraps


# fuction decorator
class Runtime:
    def __init__(self, prec=6):
        self._prec = prec

    def __call__(self, func):
        @wraps(func)
        def runtime_wrapper(*args, **kwargs):
            import time
            start = time.time()
            ret = func(*args, **kwargs)
            end = time.time()

            print(f'elapsed time: {end - start:.{self._prec}f} seconds')
            return ret

        return runtime_wrapper


# fuction decorator
def profile(func):
    @wraps(func)
    def profile_wrapper(*args, **kwargs):
        import cProfile
        prof = cProfile.Profile()
        ret = prof.runcall(func, *args, **kwargs)
        prof.print_stats()

        return ret

    return profile_wrapper


if __name__ == '__main__':
    import cProfile
    import os.path

    filename = input('Python file name: ')
    name, suffix = os.path.splitext(filename)

    if not suffix:
        suffix = 'py'
        filename += '.' + suffix

    if suffix == 'py' and os.path.exists(filename):
        # $ python -m cProfile filename
        cProfile.run(filename)

 

댓글

댓글 본문
작성자
비밀번호
버전 관리
장과장02
현재 버전
선택 버전
graphittie 자세히 보기