Skip to content

Instantly share code, notes, and snippets.

@joonahn
Last active June 20, 2018 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joonahn/8fbe224fe41cd2767acf1f103f63c252 to your computer and use it in GitHub Desktop.
Save joonahn/8fbe224fe41cd2767acf1f103f63c252 to your computer and use it in GitHub Desktop.
python method profile 방법

Profile python methods

python method를 profile 하는 간단한 방법에 대한 소개

Code

우선 decorator method를 정의한다. 그 뒤 profile 대상 메소드 def 위에 @profileit decorator를 붙인다.

import cProfile

def profileit(func):
    def wrapper(*args, **kwargs):
        datafn = func.__name__ + ".profile" # Name the data file sensibly
        prof = cProfile.Profile()
        retval = prof.runcall(func, *args, **kwargs)
        prof.dump_stats(datafn)
        return retval

    return wrapper

@profileit
def function_you_want_to_profile(...)
    ...

View

프로파일 대상 파일을 돌리면 .profile 파일로 프로파일 파일이 떨어진다. 그 파일을 snakeviz로 web 상에서 확인할 수 있다.

$ sudo pip install snakeviz
$ snakeviz -H 0.0.0.0 -p 4000 -s <your_file.profile>
$ cprofilev -f <your_file.profile> -a 0.0.0.0
snakeviz web server started on 0.0.0.0:4000; enter Ctrl-C to exit
<target url>

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment