# 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)