Sign In

[Python] 성능 최적화

Y
Yerim
  1. Python

성능 최적화

코드 최적화 원리와 기법

코드 최적화: 프로그램의 실행 속도를 빠르게 하거나, 메모리 사용량으 줄이는 등 프로그램의 성능을 향상시키기 위해 코드를 변경
python 11버전: 지속해서 성능 업데이트 (이전 버전에 비해 60% 성능 향상)
리스트 대신 집합 사용 가능 → 시간 복잡도를 줄일 수 있다
# 리스트를 사용한 경우
def find_duplicates(lst):
    duplicates = []
    for item in lst:
        if lst.count(item) > 1:
            if item not in duplicates:
                duplicates.append(item)
    return duplicates
# 집합을 사용한 경우
def find_duplicate(lst):
    return list(set([item for item in lst if lst.count(item) > 1]))
numpy 는 python보다 대부분의 경우 속도가 빠르다
(100000개 이상인 경우 50배 이상의 성능을 보임)
메서드 대신 슬라이싱 구현 (메서드보다 통상 8배 정도 빠르다)
for문 대신 list comprehension을 사용하면 더 빠르다
반복문 연산이 있는 재귀는 느리다 → 메모이제이션 기법이나 functools의 lru_cache를 사용
from functools improt lru_cache

@lru_cache(maxsize=None)
def fib(num):
    if num == 0:
        return 0
    if num == 1 or num == 2:
        return 1
    else:
        return fib(num-1) + fib(num-2)

fib(50)
# 메모이제이션을 활용한 피보나치 재귀 풀이
dic = (1:1, 2:1)

def fib_name(n):
    if n in dic:
        return dic(n)
    dic[n] = fib_memo(n-1) + fib_memo(n-2)
    return dic[n]

fib_memo(6)
필요 없는 계산을 피하려고 노력
가능하다면 결과를 캐시하거나 미리 계산해둔다
파이썬 내장 함수와 라이브러리를 사용 (대부분 최적화되어 있음)

프로파일링 도구 활용

프로그램의 성능을 측정하고 분석하는 과정
Python에서는 cProfile모듈을 사용하여 실행 시간을 측정하고 가장 많은 시간을 소모하는 부분을 분석할 수 있다
import cProfile

def add(a, b):
    return a + b

def slow_function():
    total = 0
    for i in range(10000):
        total += i
        add(i, 100)
    return total

cProfile.run('slow_function()')
Yerim-DevNote
Subscribe to 'Yerim-DevNote'
Subscribe to my site to be the first to receive notifications and emails about the latest updates, including new posts.
Join Slashpage and subscribe to 'Yerim-DevNote'!
Subscribe
👍