python哪里最难用_Python 最难的函数

大家好,我是Afan

不理解单线程 与 多线程?敲几遍就好了

一、单线程 与 多线程 比较

from threading import Thread

import threading

import requests

import time

#请求任务

def request_task(url):

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}

requests.get(url,headers=headers)

time.sleep(0.5)

#获取线程名

thread_name = threading.current_thread().name

print(thread_name,'get',url)

#单线程

def singal_thread():

# 时间戳,距离1970年多少秒

start = time.time()

url = 'https://www.baidu.com/s?wd={}'

# 发送10个请求

for i in range(10):

request_task(url=url.format(i)) #调用

print('单线程耗时',time.time() - start)

#多线程

def multi_thread():

# 加入时间戳

start = time.time()

url = 'https://www.baidu.com/s?wd={}'

#线程池

thread_pool = []

for i in range(10):

t = Thread(target=request_task,args=(url.format(i),))

thread_pool.append(t)

# 开启线程任务

for i in thread_pool:

i.start()

#阻塞线程(等待线程执行完毕才执行打印语句)

for i in thread_pool:

i.join()

print('多线程耗时', time.time() - start)

if __name__ == '__main__':

# 测试单线程与多线程的速度

# singal_thread()

multi_thread()

二、多进程

from multiprocessing import Process

import os

def process_task(name):

#进程id

#获取进程号

pid = os.getpid()

#主进程

ppid = os.getppid()

print("start",name,'当前进程id',pid,'主进程id',ppid)

if __name__ == '__main__':

# 创建子进程,args参数传递列表为元组

# 注意:当元组中只有一个数据时,需要加逗号,否则为其他数据类型

p1 = Process(target=process_task,args=('afan',))

# 开始进程

p1.start()

p2 = Process(target=process_task,args=('afan2',))

p2.start()

三、进程池

import os

from multiprocessing import Pool

def fun(n):

print(os.getpid())

return n*n

if __name__ == '__main__':

#使用pool创建10个进程,过多的进程会导致系统崩溃

pool = Pool(processes=10)

list = [1,2,3,4,5,6,7,8,9,10]

#系统提供执行进程池的方式

pool.map(fun,list)

总结:一般我们使用多线程较多,速度快,多进程的使用了解下就好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值