ํ๋ก๊ทธ๋จ์ ์ฑ๋ฅ(์๊ฐ ๋ฐ ๊ณต๊ฐ ๋ณต์ก๋, ํจ์ ํธ์ถ์ ์ฃผ๊ธฐ์ ๋น๋ ๋ฑ)์ ๋ถ์ํ๋ ๊ณผ์
1. time, datetime ๋ชจ๋
2. profile ๋ชจ๋
5. cProfile๋ณด๋ค ๋ ๋๋ ค์ ์ ์ฌ์ฉ๋์ง ์์3. line_profiler
4. memory_profiler
5. cProfile ๋ชจ๋
profile๋ณด๋ค ๋น ๋ฆimport random
def generate_data(n):
"""๋๋ค ์ซ์ ๋ฆฌ์คํธ ์์ฑ"""
return [random.randint(1, 10000000) for _ in range(n)]
def sort_data(data):
"""๋ฐ์ดํฐ๋ฅผ ์ ๋ ฌ"""
sorted_data = sorted(data)
return sorted_data
def get_sum_from_data(data):
"""๋ฐ์ดํฐ ํฉ๊ณ ๊ตฌํ๊ธฐ"""
total = sum(data)
return total
def test_func():
"""๋ฐ์ดํฐ ์์ฑ โ ์ฒ๋ฆฌ โ ๊ฒฐ๊ณผ ์ถ๋ ฅ"""
data = generate_data(100000)
sorted_data = sort_data(data)
total = get_sum_from_data(sorted_data)
print(f"์ดํฉ: {total}, ์ต๋๊ฐ: {sorted_data[-1]}")
line_profiler
pip install line_profiler
from line_profiler import LineProfiler
@profile # ํ๋กํ์ผ๋ง ์ํ๋ ํจ์ ์์ ๋ฐ์ฝ๋ ์ดํฐ ์์ฑ
def test_func():
kernprof -l -v test_code.py # ํฐ๋ฏธ๋์์ ์คํ
# -l : line_profiler๋ฅผ ์ฌ์ฉํ์ฌ ์ฝ๋์ ๊ฐ ๋ผ์ธ๋ณ ์ฑ๋ฅ์ ์ถ์
# -v : ํ๋กํ์ผ๋ง ๊ฒฐ๊ณผ๋ฅผ ํ๋ฉด์ ์ถ๋ ฅ
# Hits: ๊ฐ ์ฝ๋ ๋ผ์ธ์ด ์คํ๋ ํ์
# Time: ํด๋น ๋ผ์ธ์์ ์์๋ ์๊ฐ (๋ง์ดํฌ๋ก์ด ๋จ์)
# Per Hit: ๊ฐ ํธ์ถ๋น ์์๋ ์๊ฐ
# % Time: ํด๋น ๋ผ์ธ์ด ์ ์ฒด ํจ์์์ ์ฐจ์งํ๋ ๋น์จ

memory_profiler
pip install memory_profiler
@profile # ํ๋กํ์ผ๋ง ์ํ๋ ํจ์ ์์ ๋ฐ์ฝ๋ ์ดํฐ ์์ฑ
def test_func():
python -m memory_profiler test_code.py # ํฐ๋ฏธ๋์์ ์คํ
# -m: ๋ชจ๋ ๋ชจ๋(Python ์คํฌ๋ฆฝํธ๋ฅผ memory_profiler ๋ชจ๋๋ก ์คํ)
# Mem usage: ํด๋น ๋ผ์ธ์์ ํจ์๊ฐ ์คํ๋ ๋ ์ ์ฒด ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋
# Increment: ํด๋น ๋ผ์ธ์์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ์ผ๋ง๋ ์ฆ๊ฐํ๋์ง
# Occurrences: ํด๋น ๋ผ์ธ์์ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋์ด ๋ฐ์ํ ํ์

cProfile.Profile
Python ์ฝ๋์ ์คํ ์๊ฐ์ ํ๋กํ์ผ๋งํ๋ ๋ฐ ์ฌ์ฉ
์ฃผ์ ๋ฉ์๋:
pstats.Stats
cProfile.Profile๋ก๋ถํฐ ์์ฑ๋ ํ๋กํ์ผ๋ง ๋ฐ์ดํฐ๋ฅผ ๋ถ์ํ๊ณ ์ถ๋ ฅํ๋ ๋ฐ ์ฌ์ฉ
์ฃผ์ ๋ฉ์๋:
Example
from cProfile import Profile
from pstats import Stats
profiler = Profile()
profiler.run("test_func()")
stats = Stats(profiler)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats(20)

SnakeViz๋ก cProfile ๊ฒฐ๊ณผ ์๊ฐํ ํ๊ธฐ
pip install snakeviz
snakeviz test_code.prof
