I/O密集型任务下,单线程、多进程、多线程、协程
单线程
import time def html(url): time.sleep(0.1) print(url) if __name__=='__main__': start_time = time.time() for i in range(1,1001): i = 'http://www.cnblogs.com/uncleyong/%s'%i html(i) print('---------------') print('ok') stop_time = time.time() print(stop_time - start_time)
---------------
ok
100.0597231388092
多进程
import multiprocessing import time def html(url): time.sleep(0.1) print(url) if __name__=='__main__': start_time = time.time() p_list = [] for i in range(1,1001): i = 'http://www.cnblogs.com/uncleyong/%s'%i p = multiprocessing.Process(target=html, args=(i,)) p_list.append(p) p.start() for p in p_list: p.join() print('---------------') print('ok') stop_time = time.time() print(stop_time - start_time)
---------------
ok
80.07257986068726
多线程
import threading import time def html(url): time.sleep(0.1) print(url) if __name__=='__main__': start_time = time.time() t_list = [] for i in range(1,1001): i = 'http://www.cnblogs.com/uncleyong/%s'%i t = threading.Thread(target=html, args=(i,)) t_list.append(t) t.start() for t in t_list: t.join() print('---------------') print('ok') stop_time = time.time() print(stop_time - start_time)
---------------
ok
0.23501324653625488
协程
from gevent import monkey;monkey.patch_all() import gevent import time def html(url): time.sleep(0.1) print(url) if __name__=='__main__': start_time = time.time() g_list = [] for i in range(1,1001): i = 'http://www.cnblogs.com/uncleyong/%s'%i g = gevent.spawn(html, i) g_list.append(g) for g in g_list: g.join() print('---------------') print('ok') stop_time = time.time() print(stop_time - start_time)
---------------
ok
0.14500832557678223
运行速度:协程 > 多线程 > 多进程 > 单线程
bak:https://www.cnblogs.com/uncleyong/p/8503151.html
原文:https://www.cnblogs.com/uncleyong/p/15871733.html
__EOF__
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!