From 3f6e95148e87af3ce1cba9c79b58a3e184374c10 Mon Sep 17 00:00:00 2001 From: XXIN0 <41498132+XXIN0@users.noreply.github.com> Date: Sun, 31 Dec 2023 04:57:09 +0800 Subject: [PATCH] Improve the "ASCReader" read performance. (#1717) * Update asc.py improve the "ASCReader" performance. * Update asc.py Fix: the test error "error: Item "None" of "Optional[Match[str]]" has no attribute "group" [union-attr]" * Update asc.py style: format code with "Black Code Formatter" * improvement: make regular expression compile result as module constants. * style:format import --------- Co-authored-by: XXIN --- can/io/asc.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/can/io/asc.py b/can/io/asc.py index f039cda32..07243cd5b 100644 --- a/can/io/asc.py +++ b/can/io/asc.py @@ -9,7 +9,7 @@ import re import time from datetime import datetime -from typing import Any, Dict, Generator, List, Optional, TextIO, Union +from typing import Any, Dict, Final, Generator, List, Optional, TextIO, Union from ..message import Message from ..typechecking import StringPathLike @@ -20,6 +20,14 @@ CAN_ID_MASK = 0x1FFFFFFF BASE_HEX = 16 BASE_DEC = 10 +ASC_TRIGGER_REGEX: Final = re.compile( + r"begin\s+triggerblock\s+\w+\s+(?P.+)", re.IGNORECASE +) +ASC_MESSAGE_REGEX: Final = re.compile( + r"\d+\.\d+\s+(\d+\s+(\w+\s+(Tx|Rx)|ErrorFrame)|CANFD)", + re.ASCII | re.IGNORECASE, +) + logger = logging.getLogger("can.io.asc") @@ -258,12 +266,7 @@ def __iter__(self) -> Generator[Message, None, None]: for _line in self.file: line = _line.strip() - trigger_match = re.match( - r"begin\s+triggerblock\s+\w+\s+(?P.+)", - line, - re.IGNORECASE, - ) - if trigger_match: + if trigger_match := ASC_TRIGGER_REGEX.match(line): datetime_str = trigger_match.group("datetime_string") self.start_time = ( 0.0 @@ -272,11 +275,7 @@ def __iter__(self) -> Generator[Message, None, None]: ) continue - if not re.match( - r"\d+\.\d+\s+(\d+\s+(\w+\s+(Tx|Rx)|ErrorFrame)|CANFD)", - line, - re.ASCII | re.IGNORECASE, - ): + if not ASC_MESSAGE_REGEX.match(line): # line might be a comment, chip status, # J1939 message or some other unsupported event continue