import cProfilesource = open("slow.py").read()cProfile.run(source, sort="tottime")source = """def test_me(): s = 0 for i in range(1000000): s += i**2 return stest_me()"""cProfile.run(source, sort="tottime") 4 function calls in 0.531 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.531 0.531 0.531 0.531 <string>:2(test_me) 1 0.000 0.000 0.531 0.531 {built-in method builtins.exec} 1 0.000 0.000 0.531 0.531 <string>:2(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}cProfile - профилирует вызовы функций, бесполезен при профилировании одной функцииВ IPython
%lprun -f slow_func bench() - bench вызывает slow_funс, которую профилируем построчноNumPy - библиотека для научных вычислений на Python, написана на С и Fortran
Создание двух матриц 100х100 и перемножение:
import numpy as npX = np.random.randint(0, 256, (100, 100))Y = np.random.randint(0, 256, (100, 100))X.dot(Y)PyPy - во время выполнения компилирует в машинный код наиболее часто используемый код
from numba import jitfrom numpy import arange# jit decorator tells Numba to compile this function.# The argument types will be inferred by Numba when function is called.@jitdef sum2d(arr): M, N = arr.shape result = 0.0 for i in range(M): for j in range(N): result += arr[i,j] return resulta = arange(9).reshape(3,3)print(sum2d(a))В NumPy ndarray -
X[i][j] - каждый вызов создает слайс X[i], следует писать X[i, j]Cython типизированное расширение языка Python
Оптимизирующий компилятор Python и Сython в код на C, использующий C-API интерпретатора CPython
Оптимизирующий компилятор Python и Сython в код на C, использующий C-API интерпретатора CPython