[Python] 프로파일링 cProfile, memory_profiler

2021. 11. 12. 15:55·Python/Python
728x90
반응형

프로파일링으로 병목지점 찾기

cProfile

감으로 코드를 작성하는 습관을 버리고
가설을 세우고 프로파일링을 통한 검증으로 코드를 작성해라.
이는 시간을 투자 할만한 가치가 충분하고 코드 작성의 근거가 될 수 있다.

cProfile 테스트

테스트 코드
피보나치 수열을 dp와 recursion 으로 구현한 함수

def fibonacci_dp(n):
    dp = [0, 1]
    for i in range(2, n + 1):
        dp.append(dp[i - 1] + dp[i - 2])
    return dp[n]

def fibonacci_recursion(n):
    if n <= 1:
        return n
    else:
        return fibonacci_recursion(n - 1) + fibonacci_recursion(n - 2)

num = 30
fibonacci_dp(num)
fibonacci_recursion(num)

테스트 코드 결과

당연히 recursion 이 오래 걸린다.

  • ncalls: 프로파일링 주기 동안 함수 호출 횟수
  • tottime: 함수가 실행되는 동안 소비한 초 단위 시간, 다른 함수 호출 시간은 배제
  • tottime percall: 함수를 호출하는 데 걸린 평균 시간. tottime / ncalls
  • cumtime: 함수를 실행하는 데 걸린 초 단위 누적 시간, 다른 함수 호출 시간 포함
  • cumtime percall: 함수를 호출할 때마다 걸린 시간에 대한 초 단위 평균 시간. cumtime / ncalls
C:\Script_Project\my_study>python -m cProfile -s cumulative  High-Performance-Python\2-프로파일링으로-병목지점-찾기\2-1-cProfile.py
832040
832040
         2692573 function calls (37 primitive calls) in 0.532 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.532    0.532 {built-in method builtins.exec}
        1    0.000    0.000    0.532    0.532 2-1-cProfile.py:1(<module>)
2692537/1    0.531    0.000    0.531    0.531 2-1-cProfile.py:13(fibonacci_recursion)
        2    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        1    0.000    0.000    0.000    0.000 2-1-cProfile.py:6(fibonacci_dp)
       29    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {built-in method sys.setrecursionlimit}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Memory Profiler

https://github.com/pythonprofilers/memory_profiler

pip install memory_profiler

테스트 코드

from typing import Tuple

from memory_profiler import profile


@profile
def something_method() -> Tuple[int, int]:
    a = [1] * (10 ** 5)
    b = [2] * (2 * 10 ** 6)
    c = [3] * (3 * 10 ** 7)
    del c
    return a, b

results = something_method()

테스트 결과

Line #    Mem usage    Increment  Occurences   Line Contents
============================================================
     6     89.0 MiB     89.0 MiB           1   @profile
     7                                         def something_method() -> Tuple[int, int]:
     8     89.8 MiB      0.8 MiB           1       a = [1] * (10 ** 5)
     9    105.1 MiB     15.3 MiB           1       b = [2] * (2 * 10 ** 6)
    10    333.9 MiB    228.9 MiB           1       c = [3] * (3 * 10 ** 7)
    11    105.1 MiB   -228.9 MiB           1       del c
    12    105.1 MiB      0.0 MiB           1       return a, b
728x90
반응형
저작자표시 비영리 변경금지 (새창열림)
'Python/Python' 카테고리의 다른 글
  • [Python] 튜플(tuple) 성능
  • [Python] 리스트(list) 성능
  • [Python] 검색 방법 profile 해보기
  • CentOS pyenv 설치
상쾌한기분
상쾌한기분
    반응형
    250x250
  • 상쾌한기분
    상쾌한기분
    상쾌한기분
  • 전체
    오늘
    어제
    • 분류 전체보기 (254) N
      • Python (44)
        • Python (26)
        • Django (6)
        • Flask (4)
        • Open Source (6)
      • Kotlin & Java (8)
        • Spring (2)
        • 프로젝트 (1)
      • Go (11)
      • Database (24)
        • MySQL (21)
        • Redis (3)
      • Infrastructure (29)
        • CDC (4)
        • Kafka (5)
        • Prometheus (2)
        • Fluentd (11)
        • Docker (1)
        • Airflow (2)
        • VPN (2)
      • IT (28) N
        • AI (9)
        • Langchain (8)
        • Web (18)
        • Git (8)
        • 리팩토링 (9)
        • Micro Service Architecture (8)
        • Clean Code (16)
        • Design Pattern (0)
        • 수학 (1)
        • 알고리즘 (14)
      • 책책책 책을 읽읍시다 (1)
      • OS (14)
        • Centos (10)
        • Ubuntu (3)
        • Mac (1)
      • Search Engine (2)
        • ElasticSearch (1)
        • Lucene Solr (1)
      • PHP (2)
        • Laravel (1)
        • Codeigniter (1)
  • 블로그 메뉴

    • Github 방문
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    티스토리챌린지
    MYSQL
    CDC
    http
    python
    파이썬
    LLM
    performance
    prompt
    ollama
    오블완
    Redis
    docker
    go
    Kafka
    fluentd
    git
    Golang
    백준
    Langchain
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
상쾌한기분
[Python] 프로파일링 cProfile, memory_profiler
상단으로

티스토리툴바