【问题标题】:How can I make this multi-threaded Python pinger faster?如何使这个多线程 Python pinger 更快?
【发布时间】:2018-12-06 17:43:02
【问题描述】:

我的目标:我想 ping 每个 IPv4 地址并记录他们是否响应。

我设置它的方式是每个 IP 地址都对应一个索引。例如 0.0.0.0 是索引 0,0.0.1.0 是索引 256。所以如果 0.0.0.0 响应,那么位数组的第 0 个元素为真。

代码如下:

import subprocess
from bitarray import bitarray
import threading
import time

response_array = bitarray(256 * 256 * 256 * 256)
response_array.setall(False)

def send_all_pings():
    index = 0
    for f1 in range(256):
        for f2 in range(256):
            for f3 in range(256):
                for f4 in range(256):
                    thread = PingerThread(".".join(map(str, [f1, f2, f3, f4])), index)
                    thread.start()
                    index += 1

    time.sleep(30)
    print("Writing response array to file")
    with open('responses.bin', 'wb') as out:
        response_array.tofile(out)


class PingerThread(threading.Thread):
    def __init__(self, address, index):
        threading.Thread.__init__(self)
        self.address = address
        self.index = index

    def run(self):
        if subprocess.call(["ping", "-c", "1", "-w", "1", self.address]) == 0:
            response_array[self.index] = True
        else:
            response_array[self.index] = False

我能做些什么来让它运行得更快?欢迎任何优化,即使非常小!

谢谢

【问题讨论】:

  • 最好的优化形式是与代码无关的优化:缩小范围!您可能已经知道,但没有任何场景可以 ping 所有数十亿个 IP 地址。先限制网络的范围,然后看看你对执行时间是否满意:)
  • nmap 具有扫描大地址范围的功能……

标签: python python-3.x multithreading performance optimization


【解决方案1】:

一些建议,大致按好处排序:

  1. 尽量不要启动“分叉炸弹”:您的代码会尝试启动 40 亿个线程,每个线程都会产生一个进程。这将使任何计算机瘫痪,您需要在任何时候将自己限制为(最多)几百个进程

  2. 自己编写网络代码。启动整个线程和进程以发送和接收单个网络数据包具有巨大的开销

  3. 你几乎可以肯定是 IO 受限而不是 CPU,使用异步库

假设您编写的代码能够每秒发送 10k 个数据包,这仍需要您大约 5 天的时间。如果您真的开始做某事,或者至少严格限制速率/对您产生的数据收费,如果您的 ISP 很快阻止您,我不会感到惊讶

如果您发送过多的 ping,您将不会得到响应,它们在设计上是“不可靠的”

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2013-06-04
    • 2015-11-30
    • 2023-01-14
    相关资源
    最近更新 更多