preamble
Synchronous tasks are executed sequentially, one by one, with the previous task completing before the next is executed. Asynchronous tasks may run alternatively, allowing other tasks to continue while waiting.
1. Synchronization example
Content, Content
import time
import requests
def download_url(url):
print(f"Start Download:{url}")
response = (url)
print(f"Download complete:{url}, status code:{response.status_code}")
def main():
urls = [
"",
"",
""
]
start_time = ()
for url in urls:
download_url(url)
print(f"total time consumption:{() - start_time:.2f} unit of angle or arc equivalent one sixtieth of a degree")
if __name__ == "__main__":
main()
Output:
Start of download:
Download completed:, Status code: 200
Started download:
Download completed:, Status code: 200
Started download:
Download completed:, Status Code: 200
Total time: 6.15 seconds
2. Asynchronous Example
import time
import aiohttp
import asyncio
async def download_url_async(url):
print(f"Start Download:{url}")
async with () as session:
async with (url) as response:
print(f"Download complete:{url}, status code:{}")
async def main():
urls = [
"",
"",
""
]
start_time = ()
tasks = [download_url_async(url) for url in urls]
await (*tasks)
print(f"total time consumption:{() - start_time:.2f} unit of angle or arc equivalent one sixtieth of a degree")
if __name__ == "__main__":
(main())
Output:
Start Download:
Start Download:
Started download:
Download completed:, Status code: 200
Download completed:, Status Code: 200
Download completed:, Status code: 200
Total time: 2.12 seconds
3. Summary
Synchronous operations block the program if a task has to wait (e.g., an I/O operation), resulting in a waste of resources. Asynchronous operations do not block and tasks can switch to other tasks while waiting. Full Code:/share/675ac3af-d660-8007-ae4c-e8a072867a3d