Skip to main content
 首页 » 编程设计

python之嵌套 for 循环性能低下

2025年05月04日11luoye11

我有一个相当大的文本文件(约 16k 行),我正在循环遍历每一行,检查行中是否存在客户端 IP:端口、服务器 IP:端口和关键字,使用两个 for 循环和嵌套if x in line 语句检查该行是否包含我要查找的信息。

在确定包含我要查找的值的行后,我更新了一个 sqlite 数据库。最初,由于我没有包含在手动事务中的 SQL UPDATE 语句,因此这需要花费大量时间来执行。进行此更改后,执行时间显着缩短,但我仍然发现下面的代码需要几分钟才能完成,我觉得我可怕的循环结构是原因。

如果有人有任何性能提示来帮助加快以下代码,我将不胜感激:

c.execute("SELECT client_tuple, origin_tuple FROM connections") 
# returns ~ 8k rows each with two items, clientIP:port and serverIP:port 
tuples = c.fetchall() 
 
with open('connection_details.txt', 'r') as f: 
    c.execute('BEGIN TRANSACTION') 
    # for each line in ~16k lines 
    for line in f: 
        # for each row returned from sql query 
        for tuple in tuples: 
            # if the client tuple (IP:Port) is in the line 
            if tuple[0] in line: 
                # if the origin tuple (IP:Port) is in the line 
                if tuple[1] in line: 
                    # if 'foo' is in the line 
                    if 'foo' in line: 
                        # lookup some value and update SQL with the value found 
                        bar_value = re.findall(r'(?<=bar\s).+?(?=\,)', line) 
                        c.execute("UPDATE connections " 
                                    " SET bar = ? " 
                                   "WHERE client_tuple = ? AND origin_tuple = ?", 
                                    (bar_value[0], tuple[0], tuple[1])) 
 
    conn.commit() 

请您参考如下方法:

if 'foo' in line: 检查应该在 for tuple in tuples: 迭代器之前,所以你会自动跳过不需要处理的行

第二个小改进 - compile regexp在循环外并使用已编译的匹配器。