...

/

Solution: Asynchronous Programming

Solution: Asynchronous Programming

Learn how to refactor the existing code to make it asynchronous.

We'll cover the following...

Solution overview

We have refactored our script to make it asynchronous in the following manner:

Press + to interact
import asyncio
import time
# Function to process individual items
async def process_item(item):
await asyncio.sleep(1) # Simulating a process that takes a lot of execution time
return f"Processed: {item}"
# Function to process entire data set
async def process_data(data):
# Using asyncio.gather to process the data concurrently
tasks = [process_item(item) for item in data]
return await asyncio.gather(*tasks)
async def main():
# Simulating a large amount of data
data = [i for i in range(10)]
# Processing data and noting start and end times
start_time = time.time()
processed_data = await process_data(data)
end_time = time.time()
for item in processed_data:
print(item)
# Printing execution time
print(f"Execution time: {end_time - start_time:.4f} seconds")
if __name__ == "__main__":
asyncio.run(main())

Code explanation

    ...