当前位置: 首页 > news >正文

sg.后台线程-1亿浮点运算用时-方法2

import PySimpleGUI as sg
import math
import time
import threading  # 改用标准库的 threading.Eventdef calculate_sqrt_sum(window, stop_event):"""后台计算函数"""total = 10_000_000sum_result = 0.0start_time = time.time()try:for i in range(1, total + 1):if stop_event.is_set():  # 检查是否被取消return None  # 返回 None 表示计算被取消sum_result += math.sqrt(i)# 每 100 万次更新一次进度if i % 1_000_000 == 0 or i == total:progress = i / total * 100elapsed = time.time() - start_timewindow.write_event_value('-UPDATE-', (progress, sum_result, elapsed))return (sum_result, time.time() - start_time)  # 返回结果和总用时except Exception as e:window.write_event_value('-ERROR-', str(e))return Nonedef main():stop_event = threading.Event()  # 使用 threading.Event 替代 sg.ThreadSafeEventlayout = [[sg.Text('计算 1000 万以内平方根之和')],[sg.ProgressBar(100, key='-PROGRESS-', size=(30, 20))],[sg.Multiline('', size=(40, 5), key='-OUTPUT-', autoscroll=True)],[sg.Text('结果:'), sg.Input('', key='-RESULT-', disabled=True)],[sg.Button('开始'), sg.Button('停止'), sg.Button('退出')]]window = sg.Window('多线程计算示例', layout, finalize=True)while True:event, values = window.read()if event in (sg.WIN_CLOSED, '退出'):stop_event.set()  # 通知线程停止breakelif event == '开始':window['-PROGRESS-'].update(0)window['-RESULT-'].update('')window['-OUTPUT-'].update('计算中...\n')stop_event.clear()window['开始'].update(disabled=True)window['停止'].update(disabled=False)# 启动后台任务window.perform_long_operation(lambda: calculate_sqrt_sum(window, stop_event),'-COMPLETED-')elif event == '停止':stop_event.set()  # 通知线程停止window['-OUTPUT-'].print('\n尝试停止计算...')window['停止'].update(disabled=True)elif event == '-UPDATE-':progress, result, elapsed = values[event]window['-PROGRESS-'].update(int(progress))window['-OUTPUT-'].print(f'进度: {progress:.1f}%, 已用时: {elapsed:.2f}秒')elif event == '-COMPLETED-':result = values[event]  # 获取后台任务的返回值if result is None:window['-OUTPUT-'].print('\n计算被取消或出错')else:sum_result, elapsed = resultwindow['-RESULT-'].update(f'{sum_result:.2f}')window['-OUTPUT-'].print(f'\n计算完成! 结果: {sum_result:.2f}, 总用时: {elapsed:.2f}秒')window['开始'].update(disabled=False)elif event == '-ERROR-':sg.popup_error(f'错误: {values[event]}')window['开始'].update(disabled=False)window.close()if __name__ == '__main__':main()
http://www.jsqmd.com/news/27292/

相关文章:

  • 2025 年混合机厂家最新推荐排行榜:高效盘条式无重力犁刀式锥形卧式螺带连续式等机型优选企业测评结果及核心优势解析
  • note 2
  • 基于机载相控阵天线的卫星通信链路预算示例:(一) - 实践
  • 2025年上海继承律师权威推荐榜单:离婚房产律所/离婚律所/继承律所精选服务商
  • 基于MATLAB的MFCC特征与高斯混合模型(GMM)语音识别系统
  • 安装Helm
  • vdi镜像转换vmdk虚拟磁盘文件
  • 2025 CSP/NOIp 复习
  • 卐 comes from where?
  • pypdf内存耗尽漏洞分析:恶意LZWDecode流可导致资源耗尽
  • 火山引擎多模态数据湖解决方案,以新一代数据基座迎接AI Agent时代
  • 094_尚硅谷_for循环课堂练习
  • 深入解析:Spring Cloud Netflix Ribbon:微服务的客户端负载均衡利器
  • 使用kubeasz离线安装K8S
  • sg_后台线程运行函数:.perform_long_operation(func, callback)
  • 2025年佛山短视频运营制作公司推荐:五家服务商权威测评
  • 小程序设计的底层逻辑:兰亭妙微谈 “轻产品” 如何赢得 “重体验”
  • 2025年上海离婚房产律所权威推荐榜单:离婚律所/房产律所/婚姻律所源头服务商精选
  • 2025年有实力的环保移动厕所厂家最新推荐权威榜
  • 2025年比较好的大型方便面生产线厂家推荐及采购指南
  • qoder,webstorm+通义灵码, trae,codebuddy的使用心得
  • 2025年可靠的透气三明治网布厂家最新TOP排行榜
  • Ubuntu 中的 AppArmor
  • 2025年AI在线客服新标准:如何用智能知识库实现724小时精准服务
  • 2025年口碑好的高速旋转接头行业内知名厂家排行榜
  • 2025年上海婚姻律所权威推荐榜单:继承律所/离婚事务所/离婚房产律所律师精选
  • 2025年比较好的地磅高评价厂家推荐榜
  • 2025年知名的铝方通格栅厂家最新权威推荐排行榜
  • win10+ubuntu24 双系统
  • 2025年阻燃14mm尼龙隔热条厂家最新推荐排行榜