当前位置: 首页 > 后端技术 > Python

Python最难的函数

时间:2023-03-25 22:14:13 Python

大家好,我是阿凡不懂单线程和多线程?敲几下就可以了。1.单线程和多线程比较fromthreadingimportThreadimportthreadingimportrequestsimporttime#Requesttaskdefrequest_task(url):headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/72.0.3626.121Safari/537.36'}requests.get(url,headers=headers)time.sleep(0.5)#获取线程名thread_name=threading.current_thread().nameprint(thread_name,'get',url)#单线程defsingal_thread():#时间戳,从1970年开始多少秒开始=time.time()url='https://www.baidu.com/s?wd={}'#发送10个req??uestforiinrange(10):request_task(url=url.format(i))#Callprint('单线程耗时',time.time()-start)#Multithreadingdefmulti_thread():#添加时间戳start=time.time()url='https://www.baidu.com/s?wd={}'#线程池thread_pool=[]foriinrange(10):t=Thread(target=request_task,args=(url.format(i),))thread_pool.append(t)#在thread_pool中为i开启线程任务:i.start()#阻塞线程(等待线程执行完再执行打印语句)foriinthread_pool:i.join()print('多线程耗时',time.time()-start)if__name__=='__main__':#测试单线程和多线程的速度#singal_thread()multi_thread()2.多进程frommultiprocessingimportProcessimportosdefprocess_task(name):#进程id#获取进程号pid=os.getpid()#mainprocessppid=os.getppid()print("start",name,'currentprocessid',pid,'mainprocessid',ppid)if__name__=='__main__':#创建一个子进程,args参数以元组形式传递#注意:当元组中只有一个数据时,需要加逗号,否则为另一种数据类型p1=Process(target=process_task,args=('afan',))#启动进程p1.start()p2=Process(target=process_task,args=('afan2',))p2.start()3.进程池importosfrommultiprocessingimportPooldeffun(n):print(os.getpid())返回n*nif__name__=='__main__':#使用pool创建10个进程,进程太多会导致系统崩溃pool=Pool(processes=10)list=[1,2,3,4,5,6,7,8,9,10]#系统提供了一个执行进程池pool.map(fun,list)总结的方式:一般我们用多线程比较多,速度也快。了解多进程的使用就好了。