import timeit
import re
TRIALS = 10000
data = []
def benchmark(name, func):
elapsed_time = timeit.timeit(func, number=TRIALS)
data.append([name, elapsed_time, TRIALS])
PATHS = [
"500",
"200"
]
MATCH = re.compile("^.* /api/v1/^(monitor/ping)")
def regex():
matched_routes = []
for p in PATHS:
if MATCH.match(p):
matched_routes.append(p)
PREFIXES = ["/api/v1/"]
EXCLUDES = ["/api/v1/monitor/ping"]
def prefix_match():
matched_routes = []
for p in PATHS:
# check includes
method, route = p.split(" ", 1)
for prefix in PREFIXES:
if route.startswith(prefix):
match = True
break
if not match:
continue
# check excludes
exclude_match = False
for exclude in EXCLUDES:
if route.startswith(exclude):
exclude_match = True
break
if exclude_match:
continue
matched_routes.append(p)
benchmark("regex", regex)
benchmark("prefix_match", prefix_match)
import pprint
from tabulate import tabulate
headers = ["technique", "execution_time (seconds)", "iterations"]
table_data = [headers]
table_data += sorted(data, key=lambda row: row[1])
print(tabulate(table_data, headers="firstrow"))
technique execution_time (seconds) iterations ------------ -------------------------- ------------ regex 0.0082572 10000 prefix_match 0.0196216 10000