首页 > 解决方案 > 在 python 中并行执行 asyncio 函数

问题描述

我是 python 编程的新手,我正在尝试在 python 中学习 asyncio 包以并行执行任务

这是我到目前为止尝试的代码:

import asyncio
import time
from datetime import datetime
import pandas as pd

my_list = [['1320120000000', '48596281','456'], ['1320206400000', '48596281','23259'], ['1320292800000', '50447908','4879']]
#this code is from https://djangostars.com/blog/asynchronous-programming-in-python-asyncio/

async def custom_sleep():
        print('SLEEP', datetime.now())
        #time.sleep(5)
        await asyncio.sleep(2)

async def dataextraction(textdata):
        my_list1,my_list2,my_list3=[x[0] for x in textdata],[x[1]for x in 
        textdata],[x[2] for x in textdata]
        await self.custom_sleep()
  df2=pd.DataFrame({'firstlist':my_list1,'secondlist':my_list2,'thirdlist':my_list3,'timestamp':datetime.now()})
        return df2

start = time.time()
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    tasks = [
                asyncio.ensure_future(der.dataextraction((my_list))),
             ]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    end = time.time()
    print("Total time: {}".format(end - start))

#the above code gives output as follows
SLEEP 2018-07-31 17:37:39.916922
         firstlist   secondlist   thirdlist                  timestamp
0  1320120000000    456  48596281 2018-07-31 17:37:41.920034
1  1320206400000  23259  48596281 2018-07-31 17:37:41.920034
2  1320292800000   4879  50447908 2018-07-31 17:37:41.920034
Total time: 2.0165998935699463

but i think this not correct output,all input data executed at same timestamp,but  i am looking for different time stamp values  for different input like following example:

         firstlist   secondlist   thirdlist                  timestamp
0  1320120000000    456  48596281 2018-07-31 17:37:41.760068
1  1320206400000  23259  48596281 2018-07-31 17:37:41.881064
2  1320292800000   4879  50447908 2018-07-31 17:37:41.922369
Total time: 2.0165998935699463

我跨越事件循环概念来完成上述任务,但无法弄清楚如何编码。任何帮助将不胜感激。

标签: pythonpython-3.x

解决方案


推荐阅读