Files

200 lines
8.1 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 -*-
"""分拣单件耗时实测(把整条链路的固定开销逐段量出来)。
为什么要有这个:云端识别耗时看网络和模型,本地这一堆开销(稳定判定、
抓拍编码、落盘、快照复核、提交校验、打印前释放设备)是固定的,
必须实测,才谈得上估产能。
用法(项目根目录,先关掉主程序):
python tools/measure_cycle.py # 模拟秤+模拟摄像头,10 件
python tools/measure_cycle.py --n 20 --camera real
python tools/measure_cycle.py --ident 2.5 # 模拟云端识别 2.5 秒
python tools/measure_cycle.py --print 1.8 # 假设打印占 1.8 秒
输出:各阶段平均/最大耗时,单件机器时间,加人工取放后的节拍与每小时产能。
"""
import argparse
import json
import os
import sys
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.flow import FlowEngine # noqa: E402
class StubRecog:
"""替身识别器:按 --ident 模拟云端延迟,返回名单里第一个名字"""
def __init__(self, delay):
self.delay = float(delay)
self.calls = 0
def identify(self, image_path, pending_names, timeout=8.0):
self.calls += 1
if self.delay:
time.sleep(self.delay)
return pending_names[0] if pending_names else None
def synonym_match(self, detected, candidates, timeout=4.0):
return None, '桩'
def run(cfg, n, ident, fake_print):
eng = FlowEngine(cfg, emit=lambda name, payload: None)
eng.recog = StubRecog(ident)
marks = {}
printed = [] # 打印完成的时刻(验证不再挡节拍)
orig = eng._set_state
def wrapped(state, *a, **k):
marks.setdefault(state, []).append(time.monotonic())
return orig(state, *a, **k)
eng._set_state = wrapped
if fake_print:
# 打印已异步:这里只模拟"打印机要花 N 秒",DONE 不应等它
def slow_print(item):
time.sleep(fake_print)
printed.append(time.monotonic())
eng.emit('print_result', (True, '模拟打印 %.1fs' % fake_print))
eng._do_print = slow_print
eng.start()
eng.set_station('picking')
time.sleep(1.0) # 让秤/摄像头/待办就绪
rows = eng.rows
if not rows:
print('没有待办行(server.mock 应为 true)')
eng.stop()
return None
stages = {'稳定判定': [], '抓拍': [], '识别': [], '提交': [], '打印': []}
total = []
for i in range(n):
marks.clear()
t_put = time.monotonic()
eng.scale.sim_put(0.512 + 0.001 * (i % 3))
# 等这一件走完
deadline = t_put + 60
while time.monotonic() < deadline:
if marks.get('DONE'):
break
time.sleep(0.02)
if not marks.get('DONE'):
print('第 %d 件超时(state=%s)' % (i + 1, eng.state))
eng.scale.sim_clear()
time.sleep(1.5)
continue
t_done = marks['DONE'][-1]
total.append(t_done - t_put)
detail = {
'稳定': (marks['CAPTURE'][0] - t_put) if marks.get('CAPTURE') else 0,
'抓拍': (marks['RECOGNIZE'][0] - marks['CAPTURE'][0])
if marks.get('CAPTURE') and marks.get('RECOGNIZE') else 0,
'识别': (marks['SUBMIT'][0] - marks['RECOGNIZE'][0])
if marks.get('RECOGNIZE') and marks.get('SUBMIT') else 0,
'提交': (t_done - marks['SUBMIT'][0]) if marks.get('SUBMIT') else 0,
}
print(' 第 %d 件:%s 合计 %.2fs' % (
i + 1, ' '.join('%s %.2f' % (k, v) for k, v in detail.items()),
t_done - t_put))
# 分段:CAPTURE 起算(稳定判定结束)→ RECOGNIZE → SUBMIT → DONE
if marks.get('CAPTURE') and marks.get('RECOGNIZE'):
stages['抓拍'].append(marks['RECOGNIZE'][0] - marks['CAPTURE'][0])
if marks.get('RECOGNIZE') and marks.get('SUBMIT'):
stages['识别'].append(marks['SUBMIT'][0] - marks['RECOGNIZE'][0])
if marks.get('SUBMIT') and marks.get('DONE'):
stages['提交'].append(t_done - marks['SUBMIT'][0])
# 稳定判定:从放下到进 CAPTURE(含模拟秤逼近时间,仅供参考)
if marks.get('CAPTURE'):
stages['稳定判定'].append(marks['CAPTURE'][0] - t_put)
# 取货复位
eng.scale.sim_clear()
t_idle = time.monotonic() + 8
while time.monotonic() < t_idle and eng.state != 'IDLE':
time.sleep(0.05)
time.sleep(0.15)
# 等打印队列清空(最多 10 秒),否则统计不到最后一张何时打完
t_wait = time.monotonic() + 10
while time.monotonic() < t_wait and \
getattr(eng._print_q, 'unfinished_tasks', 0):
time.sleep(0.1)
eng.stop()
def fmt(key):
v = stages[key]
if not v:
return '%s: -' % key
return '%s: 平均 %.2fs(最大 %.2fs,%d 次)' % (
key, sum(v) / len(v), max(v), len(v))
print('\n---- 实测(%d 件,识别延迟桩 %.1fs)----' % (len(total), ident))
for k in ('稳定判定', '抓拍', '识别', '提交', '打印'):
print(' ' + fmt(k))
if total:
avg = sum(total) / len(total)
print(' 单件总时长(放上→可拿走): 平均 %.2fs(最大 %.2fs)'
% (avg, max(total)))
print(' 纯机器处理(去掉稳定判定): %.2fs'
% (avg - sum(stages['稳定判定']) / max(1, len(stages['稳定判定']))))
last_done = marks['DONE'][-1] if marks.get('DONE') else 0.0
return {'stages': stages, 'total': total, 'printed': printed,
'last_done': last_done}
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--n', type=int, default=10)
ap.add_argument('--camera', default='sim', choices=['sim', 'real'])
ap.add_argument('--ident', type=float, default=0.0,
help='模拟云端识别耗时(秒),0=只测本地')
ap.add_argument('--print', dest='fake_print', type=float, default=0.0,
help='模拟标签打印耗时(秒)')
a = ap.parse_args()
cfg = json.load(open('config.json', encoding='utf-8'))
cfg['scale']['simulate'] = True
cfg['camera']['simulate'] = a.camera == 'sim'
cfg['server']['mock'] = True
cfg['printer']['enabled'] = bool(a.fake_print)
cfg['printer']['printer_name'] = 'MEASURE_FAKE' if a.fake_print else ''
cfg.setdefault('flow', {})['auto_submit'] = True
print('配置:秤=模拟,摄像头=%s,服务端=mock,打印=%s'
% ('模拟' if a.camera == 'sim' else '真实',
('模拟 %.1fs' % a.fake_print) if a.fake_print else '关'))
r = run(cfg, a.n, a.ident, a.fake_print)
if not r or not r['total']:
return
avg = sum(r['total']) / len(r['total'])
if r['printed'] and r['last_done']:
print(' 打印队列:%d 张已打完,最后一张比最后一件完成晚 %.2fs'
'(异步,不计入节拍)'
% (len(r['printed']), r['printed'][-1] - r['last_done']))
print('\n---- 产能换算 ----')
for label, ident_guess in (('快(flash 模型 + 4G/宽带)', 1.8),
('一般(8~12 秒目标区间)', 3.0),
('慢(弱网/重试一次)', 5.5)):
machine = avg - sum(r['stages']['稳定判定']) / max(
1, len(r['stages']['稳定判定'])) + ident_guess
for human in (2.0, 3.5):
cycle = machine + human
print(' %-24s 识别%.1fs + 人工取放%.1fs → 单件 %.1fs,'
'约 %d 件/时,300 件 %.0f 分钟'
% (label, ident_guess, human, cycle,
int(3600 / cycle), 300 * cycle / 60.0))
break_out = None
if break_out:
break
print('\n提示:人工取放(取走已处理货 + 放下一件并摆正)是并行不了的,'
'秤上只有一个位置,所以节拍 = 机器时间 + 人工取放时间。')
if __name__ == '__main__':
main()