Files

219 lines
7.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""v1.0.52 回归:弱机省 CPU + 卡点定位
现场主机 i5-4200U(2 核 4 线程 / 1.6GHz / 15W),用户问「为什么还是卡、
是不是 Python 的问题」。先把能确定的三处白烧 CPU / 白等 IO 掉:
A. 日志落盘不在界面线程:log() 只入队(原来每条 open+write+close,
现场杀软实时扫描时一条 3~10ms,一轮流程十几条就上百毫秒)
B. 摄像头解码按**实测耗时**自动降档:解一帧 ≥14ms → 6fps、≥8ms → 8fps;
配了 camera.decode_fps 就听配置,不再自动改
C. 预览刷新率可配(ui.preview_fps),弱机默认 6fps;同一个 Tk 图片对象
复用(paste 换像素),不再每帧新建 PhotoImage
D. _poll 每个事件处理器单独计时(ev:xxx),并且单个处理器抛异常不会
打死整个轮询(原来会,之后 after 不再调度 = 界面彻底不动)
"""
import os
import sys
import json
import time
import tempfile
import tkinter as tk
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, ROOT)
os.chdir(ROOT)
from ui import app as A # noqa: E402
# 先把真货存下来:new_app() 会把这两个方法换成空实现(不让它自己跑),
# 测试里要手动调就必须拿原来那个。
_REAL_POLL = A.App._poll
_REAL_POLL_PREVIEW = A.App._poll_preview
# 圆角图标会缓存一张 Tk 图片,同一进程开第二个 Tk 根就会报
# 「image doesn't exist」——测试里不需要它,直接关掉。
A.rounded_photo = lambda *a, **k: None
from core.evidence.frames import FrameSource, default_decode_gap # noqa: E402
ok = fail = 0
def check(name, cond, extra=''):
global ok, fail
if cond:
ok += 1
print(' ✔ %s' % name)
else:
fail += 1
print(' ✘ %s %s' % (name, extra))
BASE = json.load(open('config.json', encoding='utf-8'))
BASE.setdefault('ui', {})
BASE['ui']['mode'] = 'window'
BASE['ui']['fit_screen'] = False
BASE['ui']['borderless'] = False
def new_app(ui_extra=None, cam=None):
cfg = json.loads(json.dumps(BASE))
cfg['ui'].update(ui_extra or {})
if cam:
cfg.setdefault('camera', {}).update(cam)
A.load_config = lambda path='config.json', _c=cfg: _c
A.App._poll = lambda self: None # 不让它自己跑
A.App._poll_preview = lambda self: None
root = tk.Tk()
app = A.App(root)
root.geometry('1440x900+0+0')
for c in root.winfo_children():
c.destroy()
app._build()
root.update_idletasks()
root.update()
return root, app
print('A. 日志落盘在后台线程,界面线程只入队')
root, app = new_app()
tmp = os.path.join(tempfile.gettempdir(), '_v1052_app.log')
try:
os.remove(tmp)
except OSError:
pass
app._log_path = tmp
t0 = time.monotonic()
for i in range(500):
app.log('压测第 %d 条:识别 香菇 15.89kg → 已提交 #88231' % i)
ms = (time.monotonic() - t0) * 1000.0
check('500 条日志入队 < 200ms(单条 < 0.4ms)', ms < 200, '实际 %.1f ms' % ms)
time.sleep(1.2) # 等后台线程写盘
lines = []
if os.path.exists(tmp):
lines = open(tmp, encoding='utf-8').read().splitlines()
check('500 条都落盘了(异步不丢)', len(lines) >= 500, '实际 %d 行' % len(lines))
check('顺序保持不变', bool(lines) and '压测第 0 条' in lines[0]
and '压测第 499 条' in lines[-1], lines[:1] + lines[-1:])
check('日志行带时间戳', bool(lines) and lines[0].startswith('['), lines[:1])
print('B. 解码按实测耗时自动降档')
fs = FrameSource({'camera': {}})
check('默认档位 13fps(强机)', abs(fs.decode_gap() - 0.075) < 1e-6,
fs.decode_gap())
fs.decode_ms = 20.0 # 弱机:一帧 20ms
fs._frames_seen = 99
fs._tune_gap()
check('解一帧 20ms → 降到 ≈6fps', abs(fs.decode_gap() - 0.17) < 1e-6,
fs.decode_gap())
check('弱机标记置位(预览跟着降帧)', fs.weak is True)
check('给出解释文案', '解码一帧' in fs.perf_note, fs.perf_note)
fs2 = FrameSource({'camera': {}})
fs2.decode_ms = 9.5
fs2._frames_seen = 99
fs2._tune_gap()
check('解一帧 9.5ms → ≈8fps', abs(fs2.decode_gap() - 0.125) < 1e-6,
fs2.decode_gap())
fs3 = FrameSource({'camera': {'decode_fps': 12}})
check('配置 decode_fps 生效', abs(fs3.decode_gap() - 1 / 12.0) < 1e-6,
fs3.decode_gap())
fs3.decode_ms = 30.0
fs3._frames_seen = 99
fs3._tune_gap()
check('配置了就不自动改(人工优先)', abs(fs3.decode_gap() - 1 / 12.0) < 1e-6,
fs3.decode_gap())
check('default_decode_gap 对空配置不炸', default_decode_gap({}) > 0)
print('C. 预览刷新率可配 + 图片对象复用')
check('默认 8fps(强机)', abs(app._preview_fps() - 8.0) < 1e-6,
app._preview_fps())
check('间隔 125ms', app._preview_ms() == 125, app._preview_ms())
app.cfg['ui']['preview_fps'] = 5
check('配置 5fps 生效', abs(app._preview_fps() - 5.0) < 1e-6,
app._preview_fps())
app.cfg['ui']['preview_fps'] = 99
check('上限夹到 15fps', abs(app._preview_fps() - 15.0) < 1e-6,
app._preview_fps())
app.cfg['ui']['preview_fps'] = 0
app.engine.frames.weak = True
check('弱机自动降到 6fps', abs(app._preview_fps() - 6.0) < 1e-6,
app._preview_fps())
app.engine.frames.weak = False
# 假帧:两次同尺寸刷新必须复用同一个 PhotoImage 对象
import numpy as np # noqa: E402
app.ready = True
fake = np.zeros((720, 1280, 3), dtype=np.uint8)
fake[:, :, 1] = 90
seq = {'n': 0}
def _fake_get_frame():
seq['n'] += 1
return fake, seq['n'], time.monotonic()
app.engine.frames.get_frame = _fake_get_frame
app._poll_preview = _REAL_POLL_PREVIEW.__get__(app, A.App)
app.root.after = lambda *a, **k: None # 别真的排定时器
app._poll_preview()
first = id(app._tkimg)
app._poll_preview()
check('同一尺寸下复用同一个 Tk 图(不新建)',
app._tkimg is not None and id(app._tkimg) == first,
'%s vs %s' % (first, id(app._tkimg)))
check('预览图尺寸 = 预览框尺寸',
app._tkimg.width() == app.preview_lbl.winfo_width()
and app._tkimg.height() == app.preview_lbl.winfo_height(),
'%dx%d' % (app._tkimg.width(), app._tkimg.height()))
print('D. _poll:逐个事件计时,坏事件不打死轮询')
root.destroy()
class Boom(Exception):
pass
root2, app2 = new_app()
tmp2 = os.path.join(tempfile.gettempdir(), '_v1052_app2.log')
try:
os.remove(tmp2)
except OSError:
pass
app2._log_path = tmp2
app2.ready = True
app2.root.after = lambda *a, **k: None
called = {'n': 0}
def _on_boom(_p):
called['n'] += 1
raise Boom('故意炸一个事件')
app2._on_boom = _on_boom
app2.q.put(('boom', None))
app2.q.put(('log', '我排在坏事件后面'))
_REAL_POLL.__get__(app2, A.App)() # 不该抛出去
check('坏事件被兜住,轮询不中断', called['n'] == 1)
check('坏事件后面的日志照样处理(最近一条已更新)',
'我排在坏事件后面' in (app2.lbl_last.cget('text') or ''),
app2.lbl_last.cget('text'))
# 慢处理器必须被记一条 [dev] UI 慢帧:ev:slow
app2._prof_seen = {}
app2._on_slow = lambda p: time.sleep(0.09)
app2.q.put(('slow', None))
_REAL_POLL.__get__(app2, A.App)()
time.sleep(0.4) # 日志是异步写的,等它落盘
app2.flush_log()
_log = open(tmp2, encoding='utf-8').read() if os.path.exists(tmp2) else ''
check('慢事件被点名(ev:slow)', 'ev:slow' in _log, '日志里没有 ev:slow')
root2.destroy()
print('\n结果:%d 通过 / %d 失败' % (ok, fail))
sys.exit(1 if fail else 0)