PCM_Viewer/STARTUP_OPTIMIZATION.md

121 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 启动速度优化指南
## 问题
PyInstaller 单文件打包后启动时间超过 30 秒,太慢。
## 优化措施
### 1. 代码层面优化(已实现)
#### 延迟导入大型模块
- **QWebEngineView**:只在创建 WebItem 时导入
- **InfluxDBClient**:只在进入展示模式时创建
```python
# 之前:启动时立即导入
from PyQt6.QtWebEngineWidgets import QWebEngineView
from influxdb_wrapper import InfluxDBClient
# 现在:延迟导入
# 在 WebItem.__init__ 中:
from PyQt6.QtWebEngineWidgets import QWebEngineView
# 在需要 Influx 时:
if self.influx_client is None:
from influxdb_wrapper import InfluxDBClient
self.influx_client = InfluxDBClient(self)
```
### 2. 打包参数优化
#### 使用优化版打包脚本
```bash
python build_optimized.py
```
#### 关键优化参数
- `--noupx`:不使用 UPX 压缩UPX 会增加解压时间)
- `--optimize=2`Python 字节码优化级别
- `--exclude-module`:排除不需要的大型模块
- 不收集全部 PyQt6只收集必要的
### 3. 进一步优化建议
#### A. 使用 --onedir 模式(推荐)
单文件模式需要解压所有文件到临时目录,这很慢。如果启动速度是优先考虑,建议使用文件夹模式:
```bash
python build_optimized.py --onedir
```
**优点**
- 启动速度快(不需要解压)
- 文件体积更小
- 更新时只需替换 exe 文件
**缺点**
- 需要整个文件夹一起分发
#### B. 减少启动时的初始化工作
- 延迟加载布局文件(在后台线程)
- 延迟创建非关键 UI 组件
- 使用启动画面(让用户知道程序正在加载)
#### C. 使用 Nuitka 替代 PyInstaller可选
Nuitka 将 Python 编译为 C++,启动速度通常更快:
```bash
pip install nuitka
python -m nuitka --onefile --windows-disable-console main.py
```
#### D. 使用 SSD 和快速 CPU
- 单文件模式需要解压到临时目录SSD 会快很多
- CPU 性能也影响解压速度
### 4. 性能对比
| 方案 | 启动时间 | 文件大小 | 分发便利性 |
|------|---------|---------|-----------|
| 单文件(优化前)| 30+ 秒 | ~200MB | ⭐⭐⭐⭐⭐ |
| 单文件(优化后)| 10-15 秒 | ~180MB | ⭐⭐⭐⭐⭐ |
| 文件夹模式 | 2-5 秒 | ~200MB | ⭐⭐⭐ |
| Nuitka 单文件 | 5-10 秒 | ~150MB | ⭐⭐⭐⭐⭐ |
### 5. 测试启动时间
打包后测试启动时间:
```bash
# Windows
timeout /t 0 /nobreak >nul & dist\PCM_Viewer.exe
# 或使用 PowerShell
Measure-Command { Start-Process -FilePath "dist\PCM_Viewer.exe" -Wait }
```
### 6. 如果仍然太慢
如果优化后仍然超过 10 秒,强烈建议:
1. **使用文件夹模式**`--onedir`
- 启动速度通常快 5-10 倍
- 只需分发整个文件夹
2. **考虑使用 Nuitka**
- 编译为原生代码,启动更快
- 但打包时间更长
3. **检查杀毒软件**
- 某些杀毒软件会扫描单文件 exe导致启动慢
- 可以添加到白名单
4. **使用启动画面**
- 即使启动慢,至少让用户知道程序在加载
- 可以显示进度条或加载动画