golang控制檯顯示進度條

進度條元素

[X] 總量
[X] 當前進度
[X] 耗時

通過以上元素可以延伸出:完成百分比、速度、預計剩餘時間、根據設置速度快慢閾值用不同的顏色來顯示進度條。

實現

// 進度條
type Bar struct {
    mu       sync.Mutex
    line     int                   //顯示在哪行  多進度條的時候用
    prefix   string                //進度條前置描述
    total    int                   //總量
    width    int                   //寬度
    advance  chan bool             //是否刷新進度條
    done     chan bool             //是否完成
    currents map[string]int        //一段時間內每個時間點的完成量
    current  int                   //當前完成量
    rate     int                   //進度百分比
    speed    int                   //速度
    cost     int                   //耗時
    estimate int                   //預計剩餘完成時間
    fast     int                   //速度快的閾值
    slow     int                   //速度慢的閾值
}

細節控制

耗時

一個計時器,需要注意的是即使進度沒有變化,耗時也是遞增的,看過一個多進程進度條的寫法,沒有注意這塊,一個gorouting:

func (b *Bar) updateCost() {
    for {
        select {
        case <-time.After(time.Second):
            b.cost++
            b.advance <- true
        case <-b.done:
            return
        }
    }
}

進度

通過Add方法來遞增當前完成的量,然後計算相關的值:速度、百分比、剩餘完成時間等,這裏計算速度一般是取最近一段時間內的平均速度,如果是全部的完成量直接除當前耗時的話計算出來的速度並不準確,同時會影響剩餘時間的估計。

func (b *Bar) Add() {
    b.mu.Lock()
    now := time.Now()
    nowKey := now.Format("20060102150405")
    befKey := now.Add(time.Minute * -1).Format("20060102150405")
    b.current++
    b.currents[nowKey] = b.current
    if v, ok := b.currents[befKey]; ok {
        b.before = v
    }
    delete(b.currents, befKey)
    lastRate := b.rate
    lastSpeed := b.speed
    b.rate = b.current * 100 / b.total
    if b.cost == 0 {
        b.speed = b.current * 100
    } else if b.before == 0 {
        b.speed = b.current * 100 / b.cost
    } else {
        b.speed = (b.current - b.before) * 100 / 60
    }

    if b.speed != 0 {
        b.estimate = (b.total - b.current) * 100 / b.speed
    }
    b.mu.Unlock()
    if lastRate != b.rate || lastSpeed != b.speed {
        b.advance <- true
    }

    if b.rate >= 100 {
        close(b.done)
        close(b.advance)
    }
}

顯示

最簡單的直接用\r。多進度條同時展示的話需要用到終端光標移動,這裏只需要用到光標的上下移動即可,\033[nA 向上移動n行,\033[nB 向下移動n行。

移動到第n行:

func move(line int) {
    fmt.Printf("\033[%dA\033[%dB", gCurrentLine, line)
    gCurrentLine = line
}

爲了支持其他的標準輸出不影響進度條的展示,還需要提供Print, Printf, Println 的方法, 用於計算當前光標所在位置,每個進度條都會有自己的所在行,顯示的時候光標需要移動到對應的行。

源碼

https://github.com/qianlnk/pgbar

效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章