How do we profile memory, CPU load for flask API&#

2019-04-16 03:54发布

问题:

I'm using python 3 for my flask app which is running in a port 5000. It has one sample API. I need to profile memory, CPU usage while hitting this API from REST or Browser.

Please help me out for better solution.

import logging
from flask import Flask, jsonify
from flask_cors import CORS

logger = logging.getLogger()
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - "
                          "%(name)s:%(lineno)d [-] %(funcName)s- %(message)s")
logger.setLevel(logging.INFO)


app = Flask(__name__)
app.url_map.strict_slashes = False
CORS(app)


def health_check():
   return jsonify({"message": "success"})


app.add_url_rule(rule='/health', endpoint='health-check', 
    view_func=health_check, methods=['GET'])

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

回答1:

How about (see: https://pypi.org/project/memory_profiler/) :

import logging
from flask import Flask, jsonify
from flask_cors import CORS
import memory_profiler as mp   # <----

logger = logging.getLogger()
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - "
                      "%(name)s:%(lineno)d [-] %(funcName)s- %(message)s")
logger.setLevel(logging.INFO)


app = Flask(__name__)
app.url_map.strict_slashes = False
CORS(app)


@mp.profile
def health_check():
   return jsonify({"message": "success"})


app.add_url_rule(rule='/health', endpoint='health-check', 
    view_func=health_check, methods=['GET'])

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=500)

Gives:

 * Running on http://0.0.0.0:5001/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 187-502-207
Filename: mp.py

Line #    Mem usage    Increment   Line Contents
================================================
    17     40.0 MiB     40.0 MiB   @mp.profile
    18                             def health_check():
    19     40.0 MiB      0.0 MiB      return jsonify({"message": "success"})


127.0.0.1 - - [04/Jul/2018 11:01:15] "GET /health HTTP/1.1" 200 -