Python减少导入CPU的影响

时间:2018-09-09 16:47:55

标签: python import cpu-time

上下文:我正在创建一个包含面部识别的tkinter项目。因为import face_recognition, cv2需要花费很长时间,所以为了方便起见,已将其放置在线程中(我知道tkinter不喜欢线程,但它们非常有用)。例如

import tkinter
def thread_import ():
    global face_recognition, cv2
    import face_recognition, cv2
if __name__ == '__main__':
    threading.Thread (target = thread_import).start ()

我的问题是,有没有办法降低进口的影响。由于线程占用CPU时间,我的tkinter窗口可能无法响应。我不介意是否需要花费更长的时间,但是我真的不想进入所有库文件以添加time.sleep (x)

非常感谢。

1 个答案:

答案 0 :(得分:0)

非常感谢@TerryJanReedy对GIL的评论。基于此,我建立了一个multiproccessing.Process对象,并通过一个multiprocessing.Manager对象传递了必要的值。下面是一个示例实现:

import multiprocessing, time

def thread_manager (manager):
    import face_recognition, cv2
    while not manager ["closing"]:
        if manager ["com"] == 0: time.sleep (0.2)
        else:
            if manager ["com"] == 1: manager ["rtn"] = "Example return."
            manager ["com"] = 0

if __name__ == "__main__":
    manager = multiprocessing.Manager ().dict ({"com" : 0, "closing" : False, "rtn" : None})
    p = multiprocessing.Process (target = thread_manager, args = (manager,))
    p.start ()
    time.sleep (5)
    manager ["com"] = 1
    while manager ["rtn"] == None: time.sleep (0.2)
    print (manager ["rtn"])
    manager ["closing"] = True