首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang进度条

golang进度条

作者头像
李海彬
发布2018-03-19 11:44:36
2.5K0
发布2018-03-19 11:44:36
举报
文章被收录于专栏:Golang语言社区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, 以及多进度条同时展示的话需要用到终端光标移动,这里只需要用到光标的上下移动即可,\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

效果

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现
  • 细节控制
    • 耗时
      • 进度
        • 显示
        • 源码
          • 效果
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档