为什么跟随异步url打开功能比连续的慢? 在每种情况下,async_func都比sequence_exec慢。 为什么跟随异步功能花费太长时间?
在virtualbox上的Ubuntu 18.10上使用Python3.7(主机:Windows10)
import urllib.request
import asyncio
import time
urls = [
"https://www.google.co.jp",
"https://github.com",
"https://example.org",
"https://www.python.org",
"https://example.com",
"https://stackoverflow.com",
"https://ja.stackoverflow.com",
"https://httpbin.org"
]
async def url_access(url):
res = urllib.request.urlopen(url)
charset = res.info().get_content_charset()
if charset is None:
charset = "utf-8"
body = res.read()
print(body)
async def fetch():
return await asyncio.wait([url_access(i) for i in urls])
def sequential_exec():
for url in urls:
res = urllib.request.urlopen(url)
charset = res.info().get_content_charset()
if charset is None:
charset = "utf-8"
body = res.read()
print(body)
def async_func(): #async function
loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())
loop.close()
seq_start = time.time()
sequential_exec()
seq_end = time.time()
async_func_start = time.time()
async_func()
async_func_end = time.time()
print("seq_time:", seq_end - seq_start)
print("async_func_time:", async_func_end - async_func_start)
答案 0 :(得分:1)
通过async stack
实现异步。要执行的任务被压入堆栈,然后弹出并运行。
因此,如果函数是异步的,则无论如何将其首先放入async stack
中,然后从那里弹出并执行。
顺序函数立即执行。
因此,推送/弹出操作的时间延迟会增加异步功能的执行时间。