1つの線でpython 3コードを速める方法


この短い記事では、我々のコードをスピードアップするasnycioを使用します.modutilsライブラリから関数を使用して、コードにASYNCを追加することの効果と容易さを示します.
以下に例をあげます.これは、asyncIOのポイントを証明するためだけの基本的な例です.これは、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 to get all responsesここでは、この例を更新して、asyncioを使用して1の代わりに1度に16個のレスポンスを取得します.これは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 to get all responses使用aioloop 機能からmodutils 我々は我々のコードをスピードアップすることができました、そして、何がほとんど瞬間をとったかについて確認してください.
注意: aioloop関数では、与えられた関数にそれぞれの内部項目を展開する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について詳しく知るhere .