同步异步对比

前言

同步的任务逐个按顺序执行,前一个任务完成后才执行下一个任务。异步的任务可交替运行,允许其他任务在等待期间继续执行。

1.同步示例

内容,内容

import time
import requests

def download_url(url):
    print(f"开始下载:{url}")
    response = requests.get(url)
    print(f"下载完成:{url}, 状态码:{response.status_code}")

def main():
    urls = [
        "https://www.example.com",
        "https://www.python.org",
        "https://www.openai.com"
    ]
    start_time = time.time()
    for url in urls:
        download_url(url)
    print(f"总耗时:{time.time() - start_time:.2f} 秒")

if __name__ == "__main__":
    main()

输出:

开始下载:https://www.example.com
下载完成:https://www.example.com, 状态码:200
开始下载:https://www.python.org
下载完成:https://www.python.org, 状态码:200
开始下载:https://www.openai.com
下载完成:https://www.openai.com, 状态码:200
总耗时:6.15 秒

2.异步示例

import time
import aiohttp
import asyncio

async def download_url_async(url):
    print(f"开始下载:{url}")
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            print(f"下载完成:{url}, 状态码:{response.status}")

async def main():
    urls = [
        "https://www.example.com",
        "https://www.python.org",
        "https://www.openai.com"
    ]
    start_time = time.time()
    tasks = [download_url_async(url) for url in urls]
    await asyncio.gather(*tasks)
    print(f"总耗时:{time.time() - start_time:.2f} 秒")

if __name__ == "__main__":
    asyncio.run(main())

输出:

开始下载:https://www.example.com
开始下载:https://www.python.org
开始下载:https://www.openai.com
下载完成:https://www.example.com, 状态码:200
下载完成:https://www.python.org, 状态码:200
下载完成:https://www.openai.com, 状态码:200
总耗时:2.12 秒

3.总结

同步操作如果某个任务需要等待(如 I/O 操作),会阻塞程序,导致资源浪费。异步操作不会阻塞,任务在等待时可以切换到其他任务。完整代码:https://chatgpt.com/share/675ac3af-d660-8007-ae4c-e8a072867a3d