美文网首页
【Python学习】⼀个并行化的ping程序

【Python学习】⼀个并行化的ping程序

作者: 时间煮菜 | 来源:发表于2020-03-17 21:14 被阅读0次

⼀个并行化的ping程序

  • ip.list 文件中保存了若干ip地址,写⼀个多线程程序,可以并行的ping⽂件中的ip地址,比较并行和串行ping完所有ip地址所花费的时间
  • 可以用execute_cmd, logging等学过的知识点
# encoding:GBK
import time
import os
import threading
from Queue import Queue
import logging

LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s "
DATE_FORMAT = '%Y-%m-%d  %H:%M:%S %a '
logging.basicConfig(level=logging.INFO,
                    format=LOG_FORMAT,
                    datefmt=DATE_FORMAT,
                    filename=r"D:\Python\test.log"
                    )


def ping_list():
    ip_list = ['www.baidu.com',
               'www.leetcode-cn.com',
               'www.taobao.com']
    for ip in ip_list:
        os.system('ping ' + ip)



""""
串行执行
"""""


def ping_ip():
    start_time = time.time()
    ping_list()
    logging.info('串行执行所用时间:{0}'.format(time.time() - start_time))


""""
并行执行
"""""

# 定义工作线程
WORD_THREAD = 50

# 将需要 ping 的 ip 加入队列
IP_QUEUE = Queue()
ip_list = ['www.baidu.com',
           'www.leetcode-cn.com',
           'www.taobao.com']
for ip in ip_list:
    IP_QUEUE.put(ip)


# 定义一个执行并行 ping 的函数
def ping_ip_queue():
    while not IP_QUEUE.empty():
        ip = IP_QUEUE.get()
        os.system('ping ' + ip)


def ping_threading():
    threads = []
    start_time = time.time()
    for i in range(WORD_THREAD):
        thread = threading.Thread(target=ping_ip_queue)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    logging.info('并行执行所用时间:{0}'.format(time.time() - start_time))


if __name__ == '__main__':
    ping_ip()
    ping_threading()

执行截图:


相关文章

  • 【Python学习】⼀个并行化的ping程序

    ⼀个并行化的ping程序 ip.list 文件中保存了若干ip地址,写⼀个多线程程序,可以并行的ping⽂件中的i...

  • 3.1 NumPy介绍及导入

    Python在科学计算方面提供了完备的程序扩展库,包括机器学习、数学分析、可视化库、GPU并行库等。Continu...

  • Python编写udp协议的ping程序方法

    今天小编给大家分享的是扣丁学堂Python在线学习课程:使用Python编写udp协议的ping程序方法,别的不多...

  • Python实现Ping程序

    Ping简介 PING (Packet Internet Groper),网络包探索器,用于测试网络连接量的程序 ...

  • 一行 Python 代码实现并行

    Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才...

  • 一行 Python 代码实现并行

    Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才...

  • 一行 Python 代码实现并行

    Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才...

  • 一行 Python 代码实现并行,骚技能,Get!

    Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才...

  • 一行 Python 代码实现并行

    Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得错误的教学指导才...

  • [转]一行python代码实现并行

    令人窒息的骚操作Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL,我觉得...

网友评论

      本文标题:【Python学习】⼀个并行化的ping程序

      本文链接:https://www.haomeiwen.com/subject/ldoydhtx.html