# 使用yield实现单线程并发多个任务 # 引子 : 生成器回顾 # def func1(): # print('1') # yield # print('2') # yield # print('3') # yield # res = func1() # print(res) # <generator object func1 at 0x109032e60> # next(res) # 1 # next(res) # 2 # next(res) # 3 # ------------------------------------------------------ # 正式使用yield实现单线程并发多个任务 # import time # # # 加法函数 被并发的那个函数 # def func1(): # a = 1 # for i in range(1000): # a += 1 # print("a run") # yield # # def func2(): # res = func1() # b = 1 # for i in range(1000): # b += 1 # print("b run") # next(res) # # start_time = time.time() # func2() # end_time = time.time() # print("耗时>>>%s"%(end_time-start_time)) # >>>0.007849931716918945 # ------------------------------------------------------- # 不采取yield并发程序(默认运行) # import time # # # def func1(): # a = 1 # for i in range(1000): # a += 1 # print("a run") # # # def func2(): # b = 1 # for i in range(1000): # b += 1 # print("b run") # # # start_time = time.time() # func1() # func2() # end_time = time.time() # print("耗时>>>%s"%(end_time-start_time)) # # 耗时>>>0.006770133972167969 # 我们通过数值比较发现 # 使用yield生成器强行并发单线程中的函数 反而会导致运行速度下降 用时增加