#!/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)
Asynchronous Python
Async Through the Looking Glass