I want to implement async method in the following code:
import time
def main(num):
num_list = []
for i in range(num):
num_list.append(i)
print("The number that is added in list is:", i)
time.sleep(2)
return num_list
def count():
start_time = time.time()
num_list = [3,5,2,8,2]
for i in num_list:
print("\nIn count() = ", i)
data = main(i)
print("Got data from main() = ", data)
time.sleep(2)
total_time = time.time() - start_time
print("The code took",total_time,"seconds to complete")
if __name__ == "__main__":
count()
This code takes 50s to complete. I tried to implement async method in this code but I was not able to succeed because I just started learning about it. Can you tell me how can I implement async method in this code.
Here's the code where I tried to implement async method:
import asyncio, time
from asgiref.sync import sync_to_async
@sync_to_async
def main(num):
num_list = []
for i in range(num):
num_list.append(i)
print("The number that is added in list is:", i)
time.sleep(2)
return num_list
def get_data(data_var):
try:
data_var.send(None)
except StopIteration as e:
return e.value
async def count():
start_time = time.time()
num_list = [3,5,2,8,2]
for i in num_list:
print("In count() :".format(i))
task1 = asyncio.ensure_future(main(i))
data = get_data(main(i))
print("In main() = {}".format(data))
await asyncio.sleep(2)
await task1
total_time = time.time() - start_time
print("The code took",total_time, "seconds to complete")
if __name__ == "__main__":
asyncio.run(count())
And I am not getting num_list as return value instead I am getting None.