golang进度条

时间:2022-05-04
本文章向大家介绍golang进度条,主要内容包括实现、细节控制、进度、显示、源码、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
进度条元素

▪ 总量 ▪ 当前进度 ▪ 耗时

通过以上元素可以延伸出:完成百分比、速度、预计剩余时间、根据设置速度快慢阈值用不同的颜色来显示进度条。

实现

进度条

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                   //速度慢的阈值
}

细节控制

耗时

一个计时器,需要注意的是即使进度没有变化,耗时也是递增的,看过一个多进程进度条的写法,没有注意这块,一个goroutine:

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, 以及多进度条同时展示的话需要用到终端光标移动,这里只需要用到光标的上下移动即可,33[nA 向上移动n行,33[nB 向下移动n行。

移动到第n行:

func move(line int) {
    fmt.Printf("33[%dA33[%dB", gCurrentLine, line)
    gCurrentLine = line
}

为了支持其他的标准输出不影响进度条的展示,还需要提供Print, Printf, Println 的方法, 用于计算当前光标所在位置,每个进度条都会有自己的所在行,显示的时候光标需要移动到对应的行。

源码

https://github.com/qianlnk/pgbar

效果