python - 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.返回结果
解决方案
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)
祝你的项目好运!
推荐阅读
- python - Tensorflow 2:如何在自定义损失中使用张量 y_true 的形状?
- intellij-idea - IntelliJ/WebStorm 的过时 CloudFormation 模式?
- java - What re the restrictions around Java EXPLICIT type conversion?
- typescript - 当它们具有相同的名称时,如何强制打字稿将参数解释为命名空间而不是类 - gRPC
- youtube-dl - gTEHbBBl_dY:YouTube 说:无法提取视频数据
- ios - 自定义 UIView 子类中的 Swift UIView 子视图不圆角
- azure - 如何获取登录我的 Web 应用程序的用户的帐户 ID(订阅 ID)和租户 ID?
- react-native - Error when building apk with gradlew assembleRelease
- javascript - 计算开始时间为 09:00 AM 的日历天 Rails
- firebase - 使用日期从 firebase 查询中排除文档