From 9c072d6440269e46b754ff988fe10f4656cad39b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 6 Sep 2021 15:03:51 -0400 Subject: [PATCH] Replace multiple globs with single regex The existing code lists the directory contents 7 times. This usually isn't a big deal, but I'm running Octoprint on a really slow ARM board, so this ends up taking 123ms (coming out to 17ms per call). We can speed this up a lot by only listing the files once, and searching through them. With this change, this function is fast enough that it doesn't show up in the profiler --- src/octoprint/util/comm.py | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 694d180a0..c4f0f5d6e 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -188,6 +188,25 @@ regex_firmware_splitter = re.compile(r"(^|\s+)([A-Z][A-Z0-9_]*):") regex_resend_linenumber = re.compile(r"(N|N:)?(?P%s)" % regex_int_pattern) """Regex to use for request line numbers in resend requests""" +regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rfcomm).*") +"""Regex used to filter out valid tty devices""" + + +def _searchFiles(directory, pattern): + """ + Searches the directory for files matching the regex pattern + + We could use glob, but that might require multiple glob executions (and + multiple directory file listings), which can end up being slow on the + low-end devices we support. + """ + result = [] + with os.scandir(directory) as it: + for entry in it: + if pattern.match(entry.name): + result.append(entry.path) + return result + def serialList(): if os.name == "nt": @@ -204,15 +223,7 @@ def serialList(): pass else: - candidates = ( - glob.glob("/dev/ttyUSB*") - + glob.glob("/dev/ttyACM*") - + glob.glob("/dev/tty.usb*") - + glob.glob("/dev/cu.*") - + glob.glob("/dev/cuaU*") - + glob.glob("/dev/ttyS*") - + glob.glob("/dev/rfcomm*") - ) + candidates = _searchFiles("/dev", regex_serial_devices) # additional ports additionalPorts = settings().get(["serial", "additionalPorts"])