奇怪的问题,在模型推理间加入间隔导致 CPU 使用率异常的高

139 天前
 chinabrowser
from SceneDetector import SceneDetector
from multiprocessing import Pipe, Process
import numpy as np
import time
import cv2

def SceneWorker(pipe_conn, model_path, is_onnx = False):
    sd = SceneDetector(model_path, is_onnx = True)
    while True:
        data = pipe_conn.recv()
        if data is None:
            break

        results = sd.infer_scenes(data)

        pipe_conn.send(results)

if __name__ == '__main__':
    model_path = 'models/scene_model.onnx'
    scene_conn, scene_child_conn = Pipe()
    scene_process = Process(target=SceneWorker, args=(scene_child_conn, model_path, True,))
    scene_process.start()

    test_img = cv2.imread('TestImages/1440P_1000M_8X.jpg') 

    for _ in range(5000):
        scene_conn.send([test_img])
        results = scene_conn.recv()[0]
        print(results)
        time.sleep(0.1)  #这里在推理间加入了间隔

    scene_conn.send(None)
    scene_process.join()
    

推理本身时间只用不到 2ms ,连续推理时 CPU 占用率会短暂上升,推理结束后立刻归零,但是如果推理之间有间隔,则 CPU 占用则会保持在一个很高的水平。一开始以为是time.sleep的问题,后来试过了用threadingEventasyncioawait做间隔,结果也是一样的。 使用Torch或者Onnx的模型结果都是一样的,把cv预处理删除掉也不影响 CPU 使用,所以也不是cv的问题。今天还测试了把推理单独开一个进程,也没有改善。

694 次点击
所在节点    Python
3 条回复
tangtang369
139 天前
```
def SceneWorker(pipe_conn, model_path, is_onnx = False):
sd = SceneDetector(model_path, is_onnx = True)
while True:
data = pipe_conn.recv()
if data is None:
break

results = sd.infer_scenes(data)

pipe_conn.send(results)
# 在这里增加这个 你再跑下
time.sleep(0)
```
chinabrowser
139 天前
@tangtang369 `time.sleep(0)`的话可以瞬间完成
chinabrowser
139 天前
@tangtang369
500 次推理,通过管道的话是 13 秒,直接在主进程做预测是 3.7 秒,大部分时间在加载模型上
Measure-Command -Expression {python .\PipeLineTest.py}

Days : 0
Hours : 0
Minutes : 0
Seconds : 13
Milliseconds : 186
Ticks : 131865097
TotalDays : 0.000152621640046296
TotalHours : 0.00366291936111111
TotalMinutes : 0.219775161666667
TotalSeconds : 13.1865097
TotalMilliseconds : 13186.5097

Measure-Command -Expression {python .\OnnxProfiling.py}

Days : 0
Hours : 0
Minutes : 0
Seconds : 3
Milliseconds : 758
Ticks : 37589256
TotalDays : 4.35060833333333E-05
TotalHours : 0.001044146
TotalMinutes : 0.06264876
TotalSeconds : 3.7589256
TotalMilliseconds : 3758.9256

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1002611

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX