【问题标题】:Python run function in parallel to main codePython 与主代码并行运行函数
【发布时间】:2019-05-09 00:26:56
【问题描述】:

我有以下代码(Windows 64 位上的 Python 3.7):

from time import sleep
import time
from multiprocessing import Process

### function ###
def func(l):

     for i in l:
         sleep(1)
         print (i)
         t1 = time.time()
         total = t1-t0
         print ('time : ',total)


### main code ###
t0 = time.time()
l = list(range(1, 4))

if __name__ == '__main__':
     p = Process(target=func, args=(l,))
     p.start()
     p.join()

sleep(10)
print ('done')

t1 = time.time()
total = t1-t0
print ('time : ',total)

目标是让函数与主代码块并行运行。当我运行它时,我得到以下结果:

done
time :  10.000610828399658
1
time :  11.000777244567871
2
time :  12.001059532165527
3
time :  13.00185513496399
done
time :  23.11873483657837

但是我期待以下内容:

1
time: ~1
2
time: ~2
3
time: ~3
done
time: ~10

所以本质上我希望函数与主代码并行运行。我很困惑,因为没有多处理,这段代码最多应该运行 13 秒,但它运行了 23 秒。目标是让它在 10 秒内运行。

如何解决此问题以使其按预期工作?

【问题讨论】:

  • 好吧,如果你减去 10s sleep...
  • @KlausD。我认为这就是重点:他们希望并发进程在睡眠发生时运行,而不是等到它完成。
  • 将最终时间计算移到 main 中,使其仅在分叉进程后运行。
  • 非 Windows 用户可以使用 multiprocessing.set_start_method('spawn') 更改启动方法,以获得与此处观察到的 OP 相同的行为(如果您的操作系统支持 spawn)。

标签: python function multiprocessing python-multiprocessing


【解决方案1】:

我无法重现第一次打印为 ~10 的问题,当我尝试它时,我得到的时间从 ~1 开始,正如预期的那样。

我最后一次来自父进程的时间是~13。这是因为p.join(),它等待子进程完成。如果我删除它,则打印在父级中的时间约为 10。

脚本:

from time import sleep
import time
from multiprocessing import Process

### function ###
def func(l):

     for i in l:
         sleep(1)
         print (i)
         t1 = time.time()
         total = t1-t0
         print ('time : ',total)


### main code ###
t0 = time.time()
l = list(range(1, 4))

if __name__ == '__main__':
     p = Process(target=func, args=(l,))
     p.start()
     # p.join()

sleep(10)
print ('done')
t1 = time.time()
total = t1-t0
print ('time : ',total)

输出:

$ python testmultiproc.py 
1
time :  1.0065689086914062
2
time :  2.0073459148406982
3
time :  3.0085067749023438
done
time :  10.008337020874023

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多