多线程,多进程,求1-1000,0000数值的和,有callback返回值操作

# 1.自己动手计算1 + 2 + 3 + ….+ 1000 0000, 单线程计算, 多线程, 多进程, 并比较结果

import time
from functools import wraps
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool

y = 0
Ret = 0


# 装饰器用于计量时间
def count_time(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        s = time.perf_counter()
        start = time.process_time()
        r = func(*args, **kwargs)
        end = time.process_time()
        e = time.perf_counter()
        print('%s总共耗时:%s,cpu耗时:%s' % (func.__name__, e - s, end - start))
        return r

    return wrapper


# 求和, 从start+ start+1...end
def sum_from_a_b(start, end):
    ret = 0
    for i in range(start, end + 1):
        ret += i
    return ret


# 多进程版本的
@count_time
def OneThread():
    ret = sum_from_a_b(0, 10000000)
    return ret


def func_save(x):
    global y
    y += x
    print(y)


@count_time
def multi_thread():
    for i in range(10):
        # 线程池 提交任务
        thread_pools.apply_async(sum_from_a_b, args=(i * 1000000 + 1, (i + 1) * 1000000), callback=func_save)
        #callback:把执行的返回值作为参数传入callback函数
    thread_pools.close()
    thread_pools.join()


def func_save_process(x):
    global Ret
    Ret += x
    print(Ret)


@count_time
def multi_process():
    for i in range(10):
        process_pool.apply_async(sum_from_a_b, args=(i * 1000000 + 1, (i + 1) * 1000000), callback=func_save_process)
    process_pool.close()
    process_pool.join()


if __name__ == "__main__":
    thread_pools = ThreadPool()
    process_pool = Pool(10)
    ret = OneThread()
    multi_process()
    multi_thread()
    print('*' * 10)
    print(ret)
    print(y)
    print(Ret)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值