python method를 profile 하는 간단한 방법에 대한 소개
우선 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(...)
...
프로파일 대상 파일을 돌리면 .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>