В этой короткой статье мы будем использовать Asnycio для ускорения нашего кода. Мы будем использовать функцию из библиотеки Modutils, чтобы показать эффективность и простоту добавления ASNYC к вашему коду.
Вот пример код, который мы могли бы ускорить. Это основной пример, который просто предназначен для доказательства точки асинсио. Он отправит запросы в Google и вернуть ответ. Мы собираемся сделать это 32 раза и посмотреть, как долго требуется.
import requests from time import time def task(url): """ a simple task to return the response of a given url :param url: {str} -- url to send requests :return: Response object from requests """ return requests.get(url, headers={'User-Agent':'Chrome; Python'}) # timing execution start = time() # create list to store Response objects responses = [] for _ in range(0, 32): # add Response to list responses.append(task('https://www.google.com')) print(f'{time()-start} to get all responses')
Выход: 2.498640775680542 Чтобы получить все ответы
Теперь мы обновим этот пример, чтобы использовать Asyncio для извлечения 16 ответов в то время вместо 1. Это определяется max_async_pool
Переменная, которую мы устанавливаем на 16. Это может быть увеличено или уменьшилось в зависимости от желаемой скорости и системных ресурсов.
import requests from time import time from modutils import aioloop def task(url: str): """ a simple task to return the response of a given url :param url: {str} -- url to send requests :return: Response object from requests """ return requests.get(url, headers={'User-Agent': 'Chrome; Python'}) # timing execution start = time() # create a list of arguments for the task function args = [['https://www.google.com'] for _ in range(0, 32)] # sending 16 requests at one time by setting max_async_pool to 16 # responses is a list of Response objects responses = aioloop(task, args, max_async_pool=16) print(f'{time()-start} to get all responses')
Выход: 0.2680017948150635 Чтобы получить все ответы
Используя aioloop
Функция от Modutils
Мы смогли ускорить наш код и сделать то, что заняло две секунды почти мгновенно.
Примечание. Для функции AILOOP мы создали список ARGS, который распаковывает каждый внутренний элемент к данной функции. Мы также можем добавить именованные аргументы с помощью словаря в списке ARGS. Пример ниже:
import requests from time import time from modutils import aioloop def task(url: str, params: dict=None): """ a simple task to return the response of a given url :param url: {str} -- url to send requests :param params: {dict} -- optional named argument for requests parameters :return: Response object from requests """ return requests.get(url, headers={'User-Agent': 'Chrome; Python'}, params=params) # timing execution start = time() # create a list of arguments for the task function args = [['https://www.google.com', {'params':{'q':'testing'}}] for _ in range(0, 32)] # sending 16 requests at one time by setting max_async_pool to 16 # responses is a list of Response objects responses = aioloop(task, args, max_async_pool=16) print(f'{time()-start} to get all responses')
Узнайте больше о Modutils здесь Отказ
Оригинал: “https://dev.to/tannerburns/how-to-speed-up-python3-code-in-one-line-2i11”