Skip to content

Basic benchmark of flask uncovers costly line in urls.py #2406

@tonybaloney

Description

@tonybaloney

This benchmark script:

from flask import Flask


def create_app():
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__, instance_relative_config=True)

    @app.route("/hello")
    def index():
        return "Hello, World!"

    # make url_for('index') == url_for('blog.index')
    # in another app, you might define a separate main index here with
    # app.route, while giving the blog blueprint a url_prefix, but for
    # the tutorial the blog will be the main index
    app.add_url_rule("/", endpoint="index")

    return app

app = create_app()

def bench(n = 10_000):
    for _ in range(n):
        app.test_client().get("/hello")
        app.test_client().get("/")


bench()

Run with cProfile

python -m cProfile -s time bench.py

returns

        26003364 function calls (25977275 primitive calls) in 29.408 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   340012    2.902    0.000    3.460    0.000 urls.py:547(url_quote)
   140000    1.483    0.000    2.629    0.000 urls.py:457(url_parse)
   140000    0.794    0.000    1.003    0.000 urls.py:387(_unquote_to_bytes)
5147167/5147129    0.771    0.000    0.771    0.000 {built-in method builtins.isinstance}
  • 10% of the execution time is spent running url_quote()
  • url_quote is run 34 times per request
  • url_parse is run 14 times per request
  • _unquote_to_bytes is run 14 times per request.
  • isinstance() is run multiple times from each of those functions.

Running this on a line profiler shows that this line is particularly expensive. Around 6% of the overall benchmark CPU time.

https://github.com/pallets/werkzeug/blob/main/src/werkzeug/urls.py#L572

if this function could be optimized it would have a knock-on effect to Flask performance.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions