python中异步函数的并行执行

2024-05-19 08:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

我跨越eventloop的概念,以实现上述任务,但无法想出如何代码。有吗我们将非常感谢您的帮助。你知道吗


Tags: inimportloopasynciofordatetimetimemy

热门问题