Python 线程和异步
Python 线程和异步线程: cpu切换上下文协程: 用户切换上下文 Description:Example:io 处理#!/usr/bin/env python# coding: utf-8from timeit import timeitimport asyncioimport requestsfrom threading import Thre...
·
Python 线程和异步
- 线程: cpu切换上下文
- 协程: 用户切换上下文
Description:
Example:
- io 处理
#!/usr/bin/env python
# coding: utf-8
from timeit import timeit
import asyncio
import requests
from threading import Thread
import aiohttp
def call_normal():
response = [get_request_normal() for _ in range(10)]
def call_threaded():
threads = [Thread(target=get_request_normal) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
def call_async():
loop = asyncio.get_event_loop()
loop.run_until_complete(async_request(loop))
async def async_request(loop):
client = aiohttp.ClientSession(loop=loop)
request_tasks = [request_fetch(client) for _ in range(10)]
responses = await asyncio.gather(*request_tasks)
await client.close()
return responses
async def request_fetch(client):
async with client.get('https://www.csdn.net/') as resp:
response = resp.status
return response
def get_request_normal():
resp = requests.request('GET', 'https://www.csdn.net/')
return resp.status_code
if __name__ == '__main__':
a = timeit(call_normal, number=5)
print('normal:', a)
b = timeit(call_threaded, number=5)
print('threaded:', b)
c = timeit(call_async, number=5)
print('async:', c)
- cpu 处理
Remakes:
reference:
更多推荐
已为社区贡献1条内容
所有评论(0)