如何在实时接收数据时绘制filt_time与ent_time的类直方图?
实时可视化数据处理耗时的类直方图实现
核心思路
首先需要调整原代码的统计逻辑:原代码里的filt_time和ent_time是累加值,要可视化所有时间数据的分布特征,得记录每次处理的单次耗时而非累加总和,再借助matplotlib的交互模式实现实时直方图更新。
单线程实现方案
适合数据处理循环非阻塞的场景,直接在处理流程中嵌入绘图更新逻辑:
import time import matplotlib.pyplot as plt # 用列表存储单次耗时(替代原累加变量) filt_times = [] ent_times = [] # 开启matplotlib交互模式,支持实时绘图 plt.ion() # 创建双张子图分别展示两个耗时的分布 fig, (ax_filt, ax_ent) = plt.subplots(1, 2, figsize=(12, 5)) while receiving_data: # 替换为你实际的接收数据判断条件 for i in range(numBands): # 记录滤波处理的单次耗时 t_start = time.time() processing_data # 替换为你的滤波处理代码 filt_duration = time.time() - t_start filt_times.append(filt_duration) # 记录熵处理的单次耗时 t_start = time.time() processing_data # 替换为你的熵处理代码 ent_duration = time.time() - t_start ent_times.append(ent_duration) # 每处理N次更新一次绘图(避免频繁刷新卡顿,N可按需调整) if i % 5 == 0: # 更新滤波耗时直方图 ax_filt.clear() ax_filt.hist(filt_times, bins='auto', color='#1f77b4', alpha=0.7) ax_filt.set_title('滤波处理耗时分布') ax_filt.set_xlabel('耗时(秒)') ax_filt.set_ylabel('次数') # 更新熵处理耗时直方图 ax_ent.clear() ax_ent.hist(ent_times, bins='auto', color='#ff7f0e', alpha=0.7) ax_ent.set_title('熵处理耗时分布') ax_ent.set_xlabel('耗时(秒)') ax_ent.set_ylabel('次数') # 调整布局并强制刷新绘图 plt.tight_layout() plt.draw() plt.pause(0.01) # 必须暂停一小段时间让绘图引擎完成更新 # 循环结束后关闭交互模式,保留图像显示 plt.ioff() plt.show()
多线程实现方案
如果数据接收/处理是阻塞式的,建议把绘图逻辑放到单独线程,避免主线程被绘图操作阻塞:
import threading import time import matplotlib.pyplot as plt # 全局存储耗时数据,线程间共享 filt_times = [] ent_times = [] # 用于控制绘图线程退出的事件 stop_plot_event = threading.Event() def update_histograms(): plt.ion() fig, (ax_filt, ax_ent) = plt.subplots(1, 2, figsize=(12, 5)) while not stop_plot_event.is_set(): # 更新滤波耗时直方图(有数据才更新) if filt_times: ax_filt.clear() ax_filt.hist(filt_times, bins='auto', color='#1f77b4', alpha=0.7) ax_filt.set_title('滤波处理耗时分布') ax_filt.set_xlabel('耗时(秒)') ax_filt.set_ylabel('次数') # 更新熵处理耗时直方图(有数据才更新) if ent_times: ax_ent.clear() ax_ent.hist(ent_times, bins='auto', color='#ff7f0e', alpha=0.7) ax_ent.set_title('熵处理耗时分布') ax_ent.set_xlabel('耗时(秒)') ax_ent.set_ylabel('次数') plt.tight_layout() plt.draw() plt.pause(0.1) # 调整刷新间隔,平衡实时性和性能 plt.ioff() plt.show() # 启动绘图线程 plot_thread = threading.Thread(target=update_histograms, daemon=True) plot_thread.start() # 主数据处理循环 try: while receiving_data: for i in range(numBands): # 记录滤波单次耗时 t_start = time.time() processing_data # 替换为你的滤波处理代码 filt_times.append(time.time() - t_start) # 记录熵处理单次耗时 t_start = time.time() processing_data # 替换为你的熵处理代码 ent_times.append(time.time() - t_start) finally: # 停止绘图线程 stop_plot_event.set() plot_thread.join()
关键注意事项
- 单次耗时记录:必须用列表存储每次的耗时,而非累加值,这样直方图才能展示所有时间数据的分布特征;
- 交互模式依赖:
plt.ion()是实时绘图的核心,plt.pause()是强制刷新绘图的必要操作,缺一不可; - 刷新频率控制:不要每次处理都刷新绘图,设置固定间隔可以避免程序卡顿;
- 多线程安全:列表的
append操作在Python中是线程安全的,无需额外加锁,若有更复杂的共享操作则需考虑锁机制。
内容的提问来源于stack exchange,提问作者forzalupi1912
相关产品推荐
相关产品推荐

