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 asyncioimport time# Function to process individual itemsasync def process_item(item):await asyncio.sleep(1) # Simulating a process that takes a lot of execution timereturn f"Processed: {item}"# Function to process entire data setasync def process_data(data):# Using asyncio.gather to process the data concurrentlytasks = [process_item(item) for item in data]return await asyncio.gather(*tasks)async def main():# Simulating a large amount of datadata = [i for i in range(10)]# Processing data and noting start and end timesstart_time = time.time()processed_data = await process_data(data)end_time = time.time()for item in processed_data:print(item)# Printing execution timeprint(f"Execution time: {end_time - start_time:.4f} seconds")if __name__ == "__main__":asyncio.run(main())