Skip to content

Instantly share code, notes, and snippets.

@mmattamala
Forked from matthewfeickert/README.md
Last active May 2, 2024 08:21
Show Gist options
  • Save mmattamala/a81496089f83138b1f0774fc7a35275a to your computer and use it in GitHub Desktop.
Save mmattamala/a81496089f83138b1f0774fc7a35275a to your computer and use it in GitHub Desktop.
Simple cProfile example with snakeviz
import cProfile
from scipy.optimize import minimize
def main():
# c.f. https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html
func = lambda x: (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
x0 = (2, 0)
constraints = (
{"type": "ineq", "fun": lambda x: x[0] - 2 * x[1] + 2},
{"type": "ineq", "fun": lambda x: -x[0] - 2 * x[1] + 6},
{"type": "ineq", "fun": lambda x: -x[0] + 2 * x[1] + 2},
)
bounds = ((0, None), (0, None))
result = minimize(func, x0, method="SLSQP", bounds=bounds, constraints=constraints)
print(f"result:\n{result}")
print(f"best fit parameters: {result.x}")
if __name__ == "__main__":
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
profiler.dump_stats("example.prof")

Simple cProfile example with snakeviz

Environment Setup

Make a Python virtual environment and install the dependencies

python -m pip install --upgrade pip setuptools wheel
python -m pip install scipy~=1.7.1 snakeviz~=2.1.0

Run

  1. First run the example to generate the cProfile profile file
python example.py
  1. Then run snakeviz over the profile file to interact with the profile information
snakeviz example.prof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment