{ "cells": [ { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import timeit\n", "import re\n", "\n", "TRIALS = 10000\n", "data = []\n", "\n", "def benchmark(name, func):\n", " elapsed_time = timeit.timeit(func, number=TRIALS)\n", " data.append([name, elapsed_time, TRIALS])\n", " \n", "PATHS = [\n", " \"500\",\n", " \"200\"\n", "]\n", "\n", "MATCH = re.compile(\"^.* /api/v1/^(monitor/ping)\")\n", "def regex():\n", " matched_routes = []\n", " for p in PATHS:\n", " if MATCH.match(p):\n", " matched_routes.append(p)\n", " \n", " \n", " \n", "PREFIXES = [\"/api/v1/\"]\n", "EXCLUDES = [\"/api/v1/monitor/ping\"]\n", "def prefix_match():\n", " matched_routes = []\n", " for p in PATHS:\n", " \n", " # check includes\n", " method, route = p.split(\" \", 1)\n", " for prefix in PREFIXES:\n", " if route.startswith(prefix):\n", " match = True\n", " break\n", " if not match:\n", " continue\n", " \n", " # check excludes\n", " exclude_match = False\n", " for exclude in EXCLUDES:\n", " if route.startswith(exclude):\n", " exclude_match = True\n", " break\n", " if exclude_match:\n", " continue\n", " \n", " matched_routes.append(p)\n", " \n", " \n", "benchmark(\"regex\", regex)\n", "benchmark(\"prefix_match\", prefix_match)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "technique execution_time (seconds) iterations\n", "------------ -------------------------- ------------\n", "regex 0.0082572 10000\n", "prefix_match 0.0196216 10000\n" ] } ], "source": [ "import pprint\n", "\n", "from tabulate import tabulate\n", "headers = [\"technique\", \"execution_time (seconds)\", \"iterations\"]\n", "table_data = [headers]\n", "table_data += sorted(data, key=lambda row: row[1])\n", "print(tabulate(table_data, headers=\"firstrow\"))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }