| 1 |
r"""Benchmarks for :mod:`dateparser.freshness_date_parser`. |
| 2 |
|
| 3 |
``PATTERN`` matches a number followed by a time unit, and is applied to the whole |
| 4 |
input string by ``findall()`` (in ``get_kwargs()``) and by ``sub()`` (in |
| 5 |
``_parse_time()``). Until #1335 it spelled the number as the greedy |
| 6 |
``\d+[.,]?\d*``, whose adjacent digit quantifiers backtrack without ever |
| 7 |
changing the match, so the cost grew superlinearly with the length of a digit |
| 8 |
run. #1335 made the quantifiers possessive (``\d++[.,]?\d*+``). |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
from typing import TYPE_CHECKING |
| 14 |
|
| 15 |
from dateparser.freshness_date_parser import PATTERN, freshness_date_parser |
| 16 |
from tests.benchmarks import LONG_DIGIT_RUN, TRANSLATED_RELATIVE_STRINGS |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from pytest_codspeed import BenchmarkFixture |
| 20 |
|
| 21 |
|
| 22 |
def test_freshness_pattern_findall(benchmark: BenchmarkFixture) -> None: |
| 23 |
def run(): |
| 24 |
for date_string in TRANSLATED_RELATIVE_STRINGS: |
| 25 |
PATTERN.findall(date_string) |
| 26 |
|
| 27 |
# Guard against measuring a no-op: were PATTERN to stop matching these |
| 28 |
# inputs, the benchmark would get faster instead of failing. |
| 29 |
assert PATTERN.findall(TRANSLATED_RELATIVE_STRINGS[-1]) == [ |
| 30 |
("1", "day"), |
| 31 |
(" 2", "hour"), |
| 32 |
(" 3", "minute"), |
| 33 |
(" 4", "second"), |
| 34 |
] |
| 35 |
|
| 36 |
benchmark(run) |
| 37 |
|
| 38 |
|
| 39 |
def test_freshness_pattern_findall_long_digit_run(benchmark: BenchmarkFixture) -> None: |
| 40 |
assert PATTERN.findall(LONG_DIGIT_RUN) == [] |
| 41 |
|
| 42 |
benchmark(lambda: PATTERN.findall(LONG_DIGIT_RUN)) |
| 43 |
|
| 44 |
|
| 45 |
def test_freshness_pattern_sub_long_digit_run(benchmark: BenchmarkFixture) -> None: |
| 46 |
"""``_parse_time()`` runs ``PATTERN.sub()`` over the input as well.""" |
| 47 |
assert PATTERN.sub("", LONG_DIGIT_RUN) == LONG_DIGIT_RUN |
| 48 |
|
| 49 |
benchmark(lambda: PATTERN.sub("", LONG_DIGIT_RUN)) |
| 50 |
|
| 51 |
|
| 52 |
def test_freshness_get_kwargs(benchmark: BenchmarkFixture) -> None: |
| 53 |
def run(): |
| 54 |
for date_string in TRANSLATED_RELATIVE_STRINGS: |
| 55 |
freshness_date_parser.get_kwargs(date_string) |
| 56 |
|
| 57 |
kwargs, _ = freshness_date_parser.get_kwargs(TRANSLATED_RELATIVE_STRINGS[1]) |
| 58 |
assert kwargs == {"hours": 2.0, "minutes": 50.0} |
| 59 |
|
| 60 |
benchmark(run) |