Why is the program taking so much time even after threading?
Question: I have been trying to look up for active hosts connected to a gateway with
specific masks, but it is taking a lot of time even after threading. Also the
total host are not showing correct.

CODE is:

    
    
    import subprocess, sys, threading, time, queue
    
    t = 0
    [a,b,c,d] = list(sys.argv[1].split("."))
    mask = int(sys.argv[2])
    p = queue.Queue()
    
    def alive(host):
        reply = str(subprocess.Popen(["ping", "-n","1","-w","5",host],
                              stdout=subprocess.PIPE).communicate()[0])
    
        if "TTL=" in reply :
            if host != sys.argv[1]:
                print(host," is UP")
                p.put(1)
            else:
                p.put(0)
        else:
            p.put(0)
    
    start_time = time.time()
    
    if mask == 8:
        for i in range(1,256):
            for j in range(1,256):
                for k in range(1,256):
                    iplist = [a,str(i),str(j),str(k)]
                    ip = '.'.join(iplist)
                    thread = threading.Thread(target = alive(ip))
                    thread.start()
    
    elif mask == 16:
        for i in range(1,256):
            for j in range(1,256):
                    iplist = [a,b,str(i),str(j)]
                    ip = '.'.join(iplist)
                    thread = threading.Thread(target = alive(ip))
                    thread.start()
    
    elif mask == 24:
        for i in range(1,256):
            iplist = [a,b,c,str(i)]
            ip = '.'.join(iplist)
            thread = threading.Thread(target = alive(ip))
            thread.start()
    
    else:
        print("Mask must be 8 , 16 or 24")
    
    for i in range(p.qsize()):
        if p.get == 1:
            t+=1
        else:
            pass
    
    print("\nTotal no. of hosts connected to ",sys.argv[1], " is ",t)
    print("Total time taken is ",time.time() - start_time)
    

COMMAND LINE INPUT:

    
    
    python uphost.py 192.168.1.1 24
    

OUTPUT:

    
    
    192.168.1.20  is UP
    192.168.1.30  is UP
    
    Total no. of hosts connected to  192.168.1.1  is  0
    Total time taken is  125.90091395378113
    


Answer: You are creating way over too many threads (256, 256^2, 256^3). And thread
creation has an overhead which you need to balance with the amount of work
each thread is doing.

I think a better solution is to use a Thread pool (see
<https://docs.python.org/2/library/multiprocessing.html#module-
multiprocessing.pool>) with a predetermined number (as many as the number of
threads your machine supports).

