Skip to content

Instantly share code, notes, and snippets.

@matthewfeickert
Created September 27, 2021 21:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewfeickert/dd6e7a5fda1ed1e3498219dafe5f9ea1 to your computer and use it in GitHub Desktop.
Save matthewfeickert/dd6e7a5fda1ed1e3498219dafe5f9ea1 to your computer and use it in GitHub Desktop.
Simple cProfile example with snakeviz

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 -r requirements.txt

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
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")
scipy~=1.7.1
snakeviz~=2.1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment