简体   繁体   English

使用Python每5秒在每个项目上并行运行一个函数

[英]Run a function on each item in parallel every 5 seconds with Python

I am processing a video and want to check multiple regions of interest in parallel, every 5 seconds. 我正在处理视频,并希望每5秒并行检查多个感兴趣的区域。 I would like to know if the function I currently have is accomplishing this in the correct manner. 我想知道我当前拥有的功能是否以正确的方式完成了此任务。

def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        for region in regions:
            threading.Thread(target=processRegion, args=(frame, region, index)).start()
            index += 1

Right now I can't really tell if all of the regions are being processed in parallel (although I know that they are all being processed). 现在,我无法真正判断是否所有区域都正在并行处理(尽管我知道它们都在并行处理中)。 The program runs pretty slow here compared to when I'm purposely checking the regions right after the other. 与我有目的地检查其他区域时相比,该程序在这里运行非常慢。 The processing for all the regions don't have to start at the same time. 所有区域的处理不必同时开始。

是的,此代码似乎每5秒并行启动N个线程,但是由于Python的全局解释器锁 ,它的执行速度不会比检查N个区域的单个线程快。

You are currently creating 6 new threads for each iteration (1 checkFrames and 5 processRegion ). 当前,您正在为每个迭代创建6个新线程(1个checkFrames和5个processRegion )。 Creating a threads is time and resources consuming. 创建线程很耗时间和资源。 What I suggest is to create 5 threads that will process each every 5 seconds 我建议创建5个线程,每5秒处理一次

def checkFrame(frame, region, index):
    while True:
        start_time = time.time()
        processRegion(frame, region ,index)
        sleep(5 - time.time() - start_time)
for region in len(regions):
    threading.Thread(target=checkFrame, args=(frame, region, index)).start()

This code assumes that a processRegion call takes under 5 seconds. 此代码假定processRegion调用花费的时间少于5秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM