Codebase list golang-github-vbauerster-mpb / eff1034
merge example Vladimir Bauer 7 years ago
1 changed file(s) with 94 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 package main
1
2 import (
3 "fmt"
4 "math/rand"
5 "sync"
6 "time"
7
8 "github.com/vbauerster/mpb/v4"
9 "github.com/vbauerster/mpb/v4/decor"
10 )
11
12 func init() {
13 rand.Seed(time.Now().UnixNano())
14 }
15
16 func main() {
17 var wg sync.WaitGroup
18 // pass &wg (optional), so p will wait for it eventually
19 p := mpb.New(mpb.WithWaitGroup(&wg))
20 total, numBars := 100, 3
21 wg.Add(numBars)
22
23 for i := 0; i < numBars; i++ {
24 name := fmt.Sprintf("Bar#%d:", i)
25 var pdecorators mpb.BarOption
26 if i == 0 {
27 pdecorators = mpb.PrependDecorators(decor.Name(name),
28 // Merge to sync width with CountersNoUnit and Percentage decorators
29 decor.Merge(
30 decor.OnComplete(variadicName(decor.WCSyncSpace), "done"),
31 decor.WCSyncSpace, // Placeholder
32 ),
33 )
34 } else {
35 pdecorators = mpb.PrependDecorators(decor.Name(name),
36 decor.CountersNoUnit("% .1d / % .1d", decor.WCSyncSpace),
37 decor.Percentage(decor.WCSyncSpace),
38 )
39 }
40 bar := p.AddBar(int64(total),
41 pdecorators,
42 mpb.AppendDecorators(
43 decor.OnComplete(
44 // ETA decorator with ewma age of 60
45 decor.EwmaETA(decor.ET_STYLE_GO, 60), "done",
46 ),
47 ),
48 )
49 // simulating some work
50 go func() {
51 defer wg.Done()
52 max := 100 * time.Millisecond
53 for i := 0; i < total; i++ {
54 start := time.Now()
55 time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
56 // ewma based decorators require work duration measurement
57 bar.IncrBy(1, time.Since(start))
58 }
59 }()
60 }
61 // Waiting for passed &wg and for all bars to complete and flush
62 p.Wait()
63 }
64
65 func variadicName(wc decor.WC) decor.Decorator {
66 wc.Init()
67 d := &varName{
68 WC: wc,
69 }
70 return d
71 }
72
73 type varName struct {
74 decor.WC
75 complete *string
76 }
77
78 func (d *varName) Decor(st *decor.Statistics) string {
79 if st.Completed && d.complete != nil {
80 return d.FormatMsg(*d.complete)
81 }
82 if st.Current < 30 {
83 return d.FormatMsg("low low low")
84 } else if st.Current < 70 {
85 return d.FormatMsg("medium medium medium")
86 } else {
87 return d.FormatMsg("high high high high high high")
88 }
89 }
90
91 func (d *varName) OnCompleteMessage(msg string) {
92 d.complete = &msg
93 }