quiet mode example
Vladimir Bauer
7 years ago
| 0 | package main | |
| 1 | ||
| 2 | import ( | |
| 3 | "flag" | |
| 4 | "fmt" | |
| 5 | "math/rand" | |
| 6 | "sync" | |
| 7 | "time" | |
| 8 | ||
| 9 | "github.com/vbauerster/mpb/v4" | |
| 10 | "github.com/vbauerster/mpb/v4/decor" | |
| 11 | ) | |
| 12 | ||
| 13 | var quietMode bool | |
| 14 | ||
| 15 | func init() { | |
| 16 | rand.Seed(time.Now().UnixNano()) | |
| 17 | flag.BoolVar(&quietMode, "q", false, "quiet mode") | |
| 18 | } | |
| 19 | ||
| 20 | func main() { | |
| 21 | flag.Parse() | |
| 22 | var wg sync.WaitGroup | |
| 23 | // pass &wg (optional), so p will wait for it eventually | |
| 24 | p := mpb.New( | |
| 25 | mpb.WithWaitGroup(&wg), | |
| 26 | mpb.ContainerOptOnCond( | |
| 27 | // setting to nil will: | |
| 28 | // set output to ioutil.Discard and disable internal refresh rate | |
| 29 | // cycling, in order to not consume much CPU, hovewer a single refresh | |
| 30 | // still will be triggered on bar complete event, per each bar. | |
| 31 | mpb.WithOutput(nil), | |
| 32 | func() bool { return quietMode }, | |
| 33 | ), | |
| 34 | ) | |
| 35 | total, numBars := 100, 3 | |
| 36 | wg.Add(numBars) | |
| 37 | ||
| 38 | for i := 0; i < numBars; i++ { | |
| 39 | name := fmt.Sprintf("Bar#%d:", i) | |
| 40 | bar := p.AddBar(int64(total), | |
| 41 | mpb.PrependDecorators( | |
| 42 | // simple name decorator | |
| 43 | decor.Name(name), | |
| 44 | // decor.DSyncWidth bit enables column width synchronization | |
| 45 | decor.Percentage(decor.WCSyncSpace), | |
| 46 | ), | |
| 47 | mpb.AppendDecorators( | |
| 48 | // replace ETA decorator with "done" message, OnComplete event | |
| 49 | decor.OnComplete( | |
| 50 | // ETA decorator with ewma age of 60 | |
| 51 | decor.EwmaETA(decor.ET_STYLE_GO, 60), "done", | |
| 52 | ), | |
| 53 | ), | |
| 54 | ) | |
| 55 | // simulating some work | |
| 56 | go func() { | |
| 57 | defer wg.Done() | |
| 58 | max := 100 * time.Millisecond | |
| 59 | for i := 0; i < total; i++ { | |
| 60 | start := time.Now() | |
| 61 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 62 | // ewma based decorators require work duration measurement | |
| 63 | bar.IncrBy(1, time.Since(start)) | |
| 64 | } | |
| 65 | }() | |
| 66 | } | |
| 67 | // Waiting for passed &wg and for all bars to complete and flush | |
| 68 | p.Wait() | |
| 69 | fmt.Println("done") | |
| 70 | } |