Python 你能帮我弄清楚为什么这个函数执行得太差吗?

Python 你能帮我弄清楚为什么这个函数执行得太差吗?,python,multithreading,re,Python,Multithreading,Re,我尝试使用Python中的线程来读取一些文件(大文件,一些文件可能超过Gig大小)并解析文件以查找特定信息,为此我使用re模块。 问题是我看到了非常高的执行时间。 读取4个以上的文件,然后分析文件中的数据需要30秒以上的时间。这是意料之中的事,或者你有什么建议可以让我在这些时候即兴发挥? 我提前道歉,我相信这已经在论坛上被问到了,我真的试图自己找到这个问题,但找不到合适的词来搜索这个问题 以下是我目前的代码: def get_hostname(file: str) -> str:

我尝试使用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)
结果是

      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复制时会出错。首先,在多个python线程中运行regex不会有多大帮助。(见附件)

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

  • 预先编译正则表达式
  • 使用
    search
    而不是
    findall
    ,因为显然您只需要第一个匹配项
  • 使用
    groups
    捕获主机名,而不是string
    split
  • 下面是我建议的
    get\u 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)
    

    请添加您的
    re
    代码。嘿,scenox没有注意到其中没有包含我的get_hostname()方法(执行我的re代码的地方)。基本上,我使用re.findall来匹配文件中的特定行,我在原始文章中添加了get_function()方法
    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)