首页 > 解决方案 > 你能帮我弄清楚为什么这个函数执行太糟糕了吗?

问题描述

我正在尝试使用 Python 中的线程来读取一些文件(大文件,其中一些可能超过 Gig 大小)并解析文件以查找特定信息,我正在使用 re 模块。问题是我看到执行时间非常长。读取超过 4 个文件,然后为我的数据解析文件需要 30 多秒。这是预期的还是您可以向我提供任何建议来改进这些时间?我提前道歉,我确定已经在论坛中问过这个问题,我真的试图自己找到这个但找不到合适的词来搜索这个问题。

以下是我当前的代码:

def get_hostname(file: str) -> str:
    """
    Get the hostname from  show tech/show running file
    :param file: show tech/show running string
    :return: the hostname as a string
    """
    hostname = re.findall('hostname.*', file, flags=re.IGNORECASE)
    if len(hostname) > 0:
        return hostname[0].split(' ')[1]
    else:
        print('Could not find a valid hostname on file ' + file)
def set_file_dictionary():
    threads_list = []
    def set_file_dictionary_thread(file_name: str):
        thread_set_file_dict_time = time.time()
        current_file = open(path + file_name, encoding='utf8', errors='ignore').read()
        files_dir[get_hostname(current_file)] = current_file
        print('set_file_dictionary_thread is ' + str(time.time() - thread_set_file_dict_time))
    for file in list_files:
        threads_list.append(threading.Thread(target=set_file_dictionary_thread, args=(file, )))
    for thread in threads_list:
        thread.start()
    for thread in threads_list:
        thread.join()

结果是

      set_file_dictionary_thread is 12.55484390258789
      set_file_dictionary_thread is 13.184206008911133
      set_file_dictionary_thread is 16.15609312057495
      set_file_dictionary_thread is 16.19360327720642
      Main exec time is 16.1940469741821

感谢您阅读我注意 - 缩进没问题,由于某种原因,从 Pycharmand 复制时它会变得混乱

标签: pythonmultithreadingre

解决方案


首先,在多个 python 线程中运行正则表达式不会有太大帮助。(见https://stackoverflow.com/a/9984414/14035728

其次,您可以通过以下方式改进您的get_hostname功能:

  1. 预先编译正则表达式
  2. 使用search而不是findall,因为显然您只需要第一个匹配项
  3. 用于groups捕获主机名,而不是字符串split

这是我建议的get_hostname功能:

hostname_re = re.compile('hostname ([^ ]*)', flags=re.IGNORECASE)
def get_hostname(file: str) -> str:
    match = hostname_re.search(file)
    if match:
        return match.groups()[0]
    else:
        print('Could not find a valid hostname on file ' + file)

推荐阅读