线程池

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# see https://www.cnblogs.com/zhang293/p/7954353.html

import time
from concurrent.futures import ThreadPoolExecutor


def say_hello(a):
    print("hello: "+a)
    time.sleep(2)


def main():
    '''测试单线程于多线程之间运行效率'''
    seed = ["a", "b", "c"]

    # 单线程运行3次 say_hello 函数
    start1 = time.time()
    for each in seed:
        say_hello(each)
    end1 = time.time()
    print("time1: " + str(end1 - start1))

    # 开启三个线程,使用 submit 提交任务
    start2 = time.time()
    with ThreadPoolExecutor(3) as executor:
        for each in seed:
            executor.submit(say_hello, each)
    end2 = time.time()
    print("time2: " + str(end2 - start2))

    # 开启三个线程,使用 map 提交任务
    start3 = time.time()
    with ThreadPoolExecutor(3) as executor1:
        executor1.map(say_hello, seed)
    end3 = time.time()
    print("time3: " + str(end3 - start3))


if __name__ == '__main__':
    main()

运行结构:

hello: a
hello: b
hello: c
time1: 6.006227016448975
hello: a
hello: b
hello: c
time2: 2.005681276321411
hello: a
hello: b
hello: c
time3: 2.005354881286621

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值