【问题标题】:python threading for nested loops用于嵌套循环的python线程
【发布时间】:2021-11-17 18:51:45
【问题描述】:

我编写了一个运行良好的程序,但是,我很确定有一种方法可以加快它的速度。

最初,我在没有从下面设置线程的情况下编写它(尽管如此,我感觉下面设置的线程根本没有效果)。

我会提前说,我对线程、处理或我的代码的任何性能改进完全陌生。

我希望有人能仔细观察下面的 sn-p,看看是否有一种方法可以实现一些东西来运行并行线程/进程等(总而言之,以加快速度或至少处理更多文件)

我在尝试获得任何其他性能加速以使用下面的嵌套 for 循环时也遇到了麻烦:

for file in files:
    for IPAddress in IPAddresses:
  • files - 是(压缩的)文件列表
  • IPAddresses - 是 IP 地址列表
if __name__ == '__main__':

    files = [
        'file1',
        'file2',
        'file3'
    ]

    IPAddresses = [
        '1.1.1.1',
        '1.1.1.2',
        '1.1.1.3'
    ]

    threads = []
    for file in files:
        for IPAddress in IPAddresses:
            t = threading.Thread(target=Search_files(file, IPAddress))
            t.start()
            threads.append(t)
            print('file: ' + file + ' processed for IP Address: ' + IPAddress.upper() + '\n')

        for thread in threads:
            thread.join()

【问题讨论】:

    标签: python multithreading performance loops nested


    【解决方案1】:

    这里是如何使用multiprocessing.Poolitertools.product 的示例:

    import multiprocessing
    from time import sleep
    from itertools import product
    
    
    files = ["file1", "file2", "file3"]
    
    IPAddresses = ["1.1.1.1", "1.1.1.2", "1.1.1.3"]
    
    
    def my_func(tpl):
        f, ip = tpl
        sleep(1)
        return f"Done {f}-{ip}!"
    
    
    if __name__ == "__main__":
        with multiprocessing.Pool() as p:
            for res in p.imap_unordered(my_func, product(files, IPAddresses)):
                print(res)
    

    在结果进入时打印(无序),应使用所有 CPU 内核:

    Done file1-1.1.1.1!
    Done file1-1.1.1.2!
    Done file3-1.1.1.2!
    Done file2-1.1.1.3!
    Done file2-1.1.1.2!
    Done file2-1.1.1.1!
    Done file1-1.1.1.3!
    Done file3-1.1.1.3!
    Done file3-1.1.1.1!
    

    【讨论】:

    • 感谢@Andrej 回复我。明天一有机会,我就去试试,谢谢。抱歉,暂时没有机会。
    • 谢谢@Andrej,我现在终于要检查了。仍然有点坚持如何准确地更改我的程序以使其正常工作,我有点理解你在上面写的内容,但我认为我需要花更多时间在上面。例如,tpl 是我猜测的元组,所以我是否打算将我的函数从:Search_file(file, IPAddress) 更改为元组?很抱歉提出基本问题。
    • 感谢@Andrej,我认为修改工作量很大,但我认为效果很好,非常感谢。老实说,我仍然遇到一个奇怪的异常情况,它似乎没有遍历文件中的每个 IP,但会继续这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多