通过线程来实现多任务并发。提高性能。先看看例子。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # @Date : 2020-03-02 21:10:39 4 # @Author : Flyinghappy (671474@qq.com) 5 # @Link : https://www.cnblogs.com/flyinghappy/ 6 # @Version : $Id$ 7 import time 8 import threading 9 import requests 10 import urllib.request 11 def runinfo(func): 12 def inner(*args): 13 print('开始访问---'+str(args[0])) 14 start_time=time.time() 15 result=func(*args) 16 stop_time=time.time() 17 print(func.__name__+'------running time is: %s'% (stop_time-start_time)) 18 print('结束访问---'+str(args[0])) 19 return result 20 return inner 21 @runinfo 22 def taskfun(url): 23 html=urllib.request.urlopen(url).read() 24 return html 25 @runinfo 26 def taskfun_outer(num_list): 27 url=[ 28 'http://www.sina.com.cn', 29 'http://www.cnr.cn', 30 'http://www.hao123.com', 31 'http://www.taobao.com', 32 'https://www.eastmoney.com' 33 ] 34 thread_list=[] 35 for i in range(len(url)): 36 t=threading.Thread(target=taskfun,args=(url[i],)) 37 thread_list.append(t) 38 for item in thread_list: 39 item.start() 40 for item in thread_list: 41 item.join() 42 43 def main(): 44 start_time=time.time() 45 num_list=['taskfun_outer'] 46 taskfun_outer(num_list) 47 stop_time=time.time() 48 print('main---running time is: %s'% (stop_time-start_time)) 49 if __name__ == '__main__': 50 main()View Code
测试结果:从用的时间看访问的任务是并发的,还可以从执行的顺序来看。