Код работает медленно, но непонятно где. Вместо того чтобы гадать — есть инструменты. Шпаргалка по всем основным.
⏱ Быстрый замер — time
import time
start = time.perf_counter()
my_function()
print(f"{time.perf_counter() - start:.4f}s")
Для грубой оценки. perf_counter() точнее чем time()
🔬 Точное сравнение — timeit
import timeit
timeit.timeit("[x**2 for x in range(1000)]", number=10000)
# В Jupyter:
%timeit my_function()
🔍 Где тормозит — cProfile
import cProfile
cProfile.run("my_function()")
# Сохранить для анализа:
cProfile.run("my_function()", "output.prof")
# В Jupyter:
%prun my_function()
Смотреть на tottime (время только в функции) и cumtime (с учётом вызовов внутри)
📋 Какая строка тормозит — line_profiler
# pip install line_profiler
@profile
def my_function():
...
kernprof -l -v script.py
# В Jupyter:
%load_ext line_profiler
%lprun -f my_function my_function()
💾 Память — memory_profiler
# pip install memory_profiler
@profile
def my_function():
...
python -m memory_profiler script.py
# В Jupyter:
%load_ext memory_profiler
%memit my_function()
📊 Визуализация — snakeviz
# pip install snakeviz
snakeviz output.prof
# Откроет браузер с интерактивной диаграммой
✅ Когда что использовать
— Где тормозит? → cProfile + snakeviz
— Какая строка? → line_profiler
— A быстрее B? → timeit
— Память утекает? → memory_profiler