首页 > 解决方案 > python线程是否可以帮助我加快执行速度?

问题描述

我的第一个解决方案:

while True:
    doLongProcess()
    # other statements
    exitCondition()

该解决方案运行速度非常慢。所以我尝试了以下解决方案:

flag = 0
while True:

if flag == 5:
    doLongProcess()
    flag = 0

# other statements
flag += 1
exitCondition()

而不是每次我将其设为 1:5 时都执行 doLongProcess()。

通过应用此解决方案,执行速度加快,但在“每个 doLongProcess()”处它会减慢。

所以我的问题是,线程编程在这种情况下会帮助我吗?如果是的话,你能指导我一点吗?

编辑: doLongProcess() 正在处理图像。如果我简短地告诉你,

1.从本地存储加载图像

2.face_recognition 库将在该图像上找到人脸位置

3.if face found:与之前的数据进行比较

4.返回结果

标签: pythonmultiprocessingpython-multiprocessing

解决方案


thrading 的全球理念是让您的计算机以更流畅的方式运行代码......它可能会更快,但这取决于您需要做什么(如果 cpu 已经处于 100% 它不会)

我认为在您的情况下,由于功能很大,它会阻止程序每 5 个循环冻结一次。

如果你想尝试线程化,这里有一个如何在 python 中使用线程的例子

import threading
import time

class MyThread (threading.Thread):
    def __init__(self, stopAt):
        threading.Thread.__init__(self) # init (master call)
        self.stopAt = stopAt

# run function of the thread (executed when calling thread.start)
    def run(self):
        # your thread code
        for i in range(0, self.stopAt):
            print("thread ", i)
            time.sleep(0.1)


m = MyThread(10)
m.start()
time.sleep(0.05)

# your main program // goes in parallel with the thread
for i in range(10):
    print("programme ", i)
    time.sleep(0.1)

祝你的项目好运!


推荐阅读