feat: 在进度条中添加内存使用量监控

- 添加实时内存使用量显示(MB)
- 实现颜色编码:绿色(<50MB)、黄色(50-100MB)、红色(>100MB)
- 优化性能:限制内存统计更新频率为每秒一次
- 支持无颜色模式兼容性
- 在所有进度条状态下显示内存信息
This commit is contained in:
ZacharyZcR 2025-08-12 16:27:39 +08:00
parent 701306ee5f
commit 245e3d0a12

View File

@ -3,6 +3,7 @@ package common
import (
"fmt"
"os"
"runtime"
"sync"
"time"
@ -37,6 +38,10 @@ type ProgressManager struct {
lastActivity time.Time
activityTicker *time.Ticker
stopActivityChan chan struct{}
// 内存监控相关
lastMemUpdate time.Time
memStats runtime.MemStats
}
var (
@ -83,6 +88,7 @@ func (pm *ProgressManager) InitProgress(total int64, description string) {
pm.enabled = true
pm.lastActivity = time.Now()
pm.spinnerIndex = 0
pm.lastMemUpdate = time.Now().Add(-2 * time.Second) // 强制首次更新内存
// 为进度条保留空间
pm.setupProgressSpace()
@ -164,7 +170,8 @@ func (pm *ProgressManager) renderProgress() {
func (pm *ProgressManager) generateProgressBar() string {
if pm.total == 0 {
spinner := pm.getActivityIndicator()
return fmt.Sprintf("%s %s 等待中...", pm.description, spinner)
memInfo := pm.getMemoryInfo()
return fmt.Sprintf("%s %s 等待中... %s", pm.description, spinner, memInfo)
}
percentage := float64(pm.current) / float64(pm.total) * 100
@ -228,12 +235,15 @@ func (pm *ProgressManager) generateProgressBar() string {
baseProgress := fmt.Sprintf("%s %s %6.1f%% %s (%d/%d)%s%s",
pm.description, spinner, percentage, bar, pm.current, pm.total, speedStr, eta)
// 添加内存信息
memInfo := pm.getMemoryInfo()
// 添加并发状态
if concurrencyStatus != "" {
return fmt.Sprintf("%s [%s]", baseProgress, concurrencyStatus)
return fmt.Sprintf("%s [%s] %s", baseProgress, concurrencyStatus, memInfo)
}
return baseProgress
return fmt.Sprintf("%s %s", baseProgress, memInfo)
}
// showCompletionInfo 显示完成信息
@ -415,3 +425,33 @@ func (pm *ProgressManager) getActivityIndicator() string {
// 如果长时间没有活动,显示旋转指示器表明程序仍在运行
return spinnerChars[pm.spinnerIndex]
}
// getMemoryInfo 获取内存使用信息
func (pm *ProgressManager) getMemoryInfo() string {
// 限制内存统计更新频率以提高性能(每秒最多一次)
now := time.Now()
if now.Sub(pm.lastMemUpdate) >= time.Second {
runtime.ReadMemStats(&pm.memStats)
pm.lastMemUpdate = now
}
// 获取当前使用的内存以MB为单位
memUsedMB := float64(pm.memStats.Alloc) / 1024 / 1024
// 根据内存使用量选择颜色
var colorCode string
if NoColor {
return fmt.Sprintf("内存:%.1fMB", memUsedMB)
}
// 根据内存使用量设置颜色
if memUsedMB < 50 {
colorCode = "\033[32m" // 绿色 - 内存使用较低
} else if memUsedMB < 100 {
colorCode = "\033[33m" // 黄色 - 内存使用中等
} else {
colorCode = "\033[31m" // 红色 - 内存使用较高
}
return fmt.Sprintf("%s内存:%.1fMB\033[0m", colorCode, memUsedMB)
}