[Python 프로파일링] py-spy와 yappi로 파이썬 코드 성능 분석하기

2024. 12. 2. 09:54·파이썬
반응형

소개

파이썬 프로그램의 성능을 분석하고 최적화하기 위해서는 프로파일링 도구가 필수적입니다. py-spy와 yappi는 각각 다른 특징을 가진 강력한 프로파일링 도구입니다. 이번 글에서는 두 도구의 사용법과 활용 방법을 자세히 알아보겠습니다.

py-spy 란?

py-spy는 파이썬 프로그램을 중단하지 않고도 실시간으로 프로파일링할 수 있는 샘플링 프로파일러입니다.

설치 방법

pip install py-spy

기본 사용법

# 프로파일링할 예제 코드
# example.py
import time

def slow_function():
    time.sleep(2)
    return "Done"

def main():
    for _ in range(3):
        slow_function()

if __name__ == "__main__":
    main()

# 프로파일링 실행
# 터미널에서:
py-spy record -o profile.svg python example.py

실시간 모니터링

# Top 형태의 실시간 모니터링
py-spy top python example.py

# 특정 프로세스 모니터링
py-spy top --pid 12345

yappi 란?

yappi는 멀티스레드 프로그램을 위한 프로파일러로, 스레드별 상세한 프로파일링 정보를 제공합니다.

설치 방법

pip install yappi

기본 사용법

import yappi
import time

def function_to_profile():
    time.sleep(1)
    return sum(i * i for i in range(1000))

# 프로파일링 시작
yappi.start()

# 코드 실행
function_to_profile()

# 프로파일링 종료
yappi.stop()

# 결과 출력
stats = yappi.get_func_stats()
stats.print_all()

# 결과를 파일로 저장
stats.save('callgrind.out', 'callgrind')

스레드 프로파일링

import yappi
import threading
import time

def worker():
    for _ in range(3):
        time.sleep(0.1)

def profile_threads():
    yappi.set_clock_type("wall")  # 실제 경과 시간 측정
    yappi.start()

    # 여러 스레드 생성
    threads = [
        threading.Thread(target=worker)
        for _ in range(3)
    ]

    # 스레드 실행
    for thread in threads:
        thread.start()

    # 스레드 종료 대기
    for thread in threads:
        thread.join()

    yappi.stop()

    # 스레드별 통계 출력
    threads_stats = yappi.get_thread_stats()
    for thread in threads_stats:
        print(
            f"Thread {thread.id}: {thread.name}, "
            f"CPU: {thread.cpu_time}, "
            f"Real: {thread.wall_time}"
        )

콜백 함수 프로파일링

import yappi

def profile_callback(func_stats, path):
    """프로파일링 결과를 처리하는 콜백"""
    with open(path, 'w') as f:
        for stat in func_stats:
            f.write(f"{stat.name}: {stat.ttot}\n")

yappi.start()

# 프로파일링할 코드 실행
your_function()

yappi.stop()

# 콜백으로 결과 처리
stats = yappi.get_func_stats()
profile_callback(stats, 'profile_results.txt')

메모리 프로파일링

import yappi
import memory_tracker

@memory_tracker.track_memory
def memory_intensive_function():
    large_list = [i for i in range(1000000)]
    return sum(large_list)

yappi.start()
memory_intensive_function()
yappi.stop()

# 메모리 사용량 통계
stats = yappi.get_func_stats()
stats.print_all(columns={
    "name": 40,
    "ncall": 5,
    "tsub": 8,
    "ttot": 8,
    "tavg": 8
})

실전 활용 예제

웹 애플리케이션 프로파일링

from flask import Flask
import yappi

app = Flask(__name__)

def profile_request(func):
    """요청 프로파일링 데코레이터"""
    def wrapper(*args, **kwargs):
        yappi.start()
        result = func(*args, **kwargs)
        yappi.stop()

        stats = yappi.get_func_stats()
        stats.save(f'profile_{func.__name__}.prof', 'pstat')
        yappi.clear_stats()

        return result
    return wrapper

@app.route('/')
@profile_request
def index():
    # 시간이 걸리는 작업 시뮬레이션
    time.sleep(0.1)
    return "Hello, World!"

병렬 처리 프로파일링

import yappi
from multiprocessing import Pool
import time

def worker_function(x):
    time.sleep(0.1)
    return x * x

def profile_parallel_processing():
    yappi.start()

    with Pool(4) as p:
        result = p.map(worker_function, range(10))

    yappi.stop()

    # 프로세스별 통계
    stats = yappi.get_func_stats()
    stats.print_all()

성능 비교 분석

import yappi
import time

def compare_implementations():
    implementations = {
        'method1': lambda: sum(i * i for i in range(10000)),
        'method2': lambda: sum(map(lambda x: x * x, range(10000)))
    }

    results = {}

    for name, impl in implementations.items():
        yappi.clear_stats()
        yappi.start()

        impl()

        yappi.stop()
        stats = yappi.get_func_stats()
        results[name] = stats[0].ttot

    return results

마치며

py-spy와 yappi는 각각의 장점이 있는 강력한 프로파일링 도구입니다. py-spy는 실시간 모니터링과 시각화에 강점이 있고, yappi는 스레드별 상세 분석에 특화되어 있습니다. 프로그램의 특성과 분석하고자 하는 성능 지표에 따라 적절한 도구를 선택하여 사용하면 효과적인 성능 최적화가 가능합니다.

저작자표시 비영리 변경금지 (새창열림)

'파이썬' 카테고리의 다른 글

파이썬 개발을 위한 VSCode 셋팅 가이드  (3) 2025.01.03
데이터 클래스 비교: dataclass vs Pydantic BaseModel  (0) 2024.12.08
SQLAlchemy: 데이터베이스 툴킷  (5) 2024.11.13
ChatGPT API의 function_call  (1) 2024.02.11
ChatGPT API를 활용한 똑똑한 채팅봇 만들기: OpenAI  (1) 2024.02.09
'파이썬' 카테고리의 다른 글
  • 파이썬 개발을 위한 VSCode 셋팅 가이드
  • 데이터 클래스 비교: dataclass vs Pydantic BaseModel
  • SQLAlchemy: 데이터베이스 툴킷
  • ChatGPT API의 function_call
코샵
코샵
나의 코딩 일기장
    반응형
  • 코샵
    끄적끄적 코딩 공방
    코샵
    • 분류 전체보기 (644) N
      • 상품 추천 (150) N
      • MongoDB (4)
      • 하드웨어 (11) N
      • 일기장 (4)
      • Unity (138)
        • Tip (41)
        • Project (1)
        • Design Pattern (8)
        • Firebase (6)
        • Asset (2)
      • 파이썬 (12)
        • Basic (41)
        • OpenCV (8)
        • Pandas (15)
        • PyQT (3)
        • SBC(Single Board Computer) (1)
        • 크롤링 (14)
        • Fast API (29)
        • Package (6)
      • Linux (4)
      • C# (97)
        • Algorithm (11)
        • Window (7)
      • TypeScript (50)
        • CSS (10)
      • Git (11)
      • SQL (5)
      • Flutter (10)
        • Tip (1)
      • System (1)
      • BaekJoon (6)
      • Portfolio (2)
      • MacOS (1)
      • 유틸리티 (1)
      • 서비스 (6)
      • 자동화 (3)
      • Hobby (10)
        • 물생활 (10)
        • 식집사 (0)
  • 인기 글

  • 태그

    codingtips
    믈레코비타멸균우유
    codingcommunity
    C#
    list
    긴유통기한우유
    스마트스토어리뷰
    스크립트 실행
    셀레니움
    programming101
    쇼핑몰리뷰
    learntocode
    ipcamera
    리뷰관리
    카페24리뷰
    appdevelopment
    리뷰이관
    스크립트 실행 순서
    유니티
    상품 리뷰 크롤링
    라떼우유
    cv2
    파이썬
    unity
    devlife
    programmerlife
    리스트
    카페24리뷰이관
    Python
    rtsp
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코샵
[Python 프로파일링] py-spy와 yappi로 파이썬 코드 성능 분석하기
상단으로

티스토리툴바