github.com/sdboyer/gps@v0.16.3/metrics.go (about)

     1  package gps
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"sort"
     8  	"text/tabwriter"
     9  	"time"
    10  )
    11  
    12  type metrics struct {
    13  	stack []string
    14  	times map[string]time.Duration
    15  	last  time.Time
    16  }
    17  
    18  func newMetrics() *metrics {
    19  	return &metrics{
    20  		stack: []string{"other"},
    21  		times: map[string]time.Duration{
    22  			"other": 0,
    23  		},
    24  		last: time.Now(),
    25  	}
    26  }
    27  
    28  func (m *metrics) push(name string) {
    29  	cn := m.stack[len(m.stack)-1]
    30  	m.times[cn] = m.times[cn] + time.Since(m.last)
    31  
    32  	m.stack = append(m.stack, name)
    33  	m.last = time.Now()
    34  }
    35  
    36  func (m *metrics) pop() {
    37  	on := m.stack[len(m.stack)-1]
    38  	m.times[on] = m.times[on] + time.Since(m.last)
    39  
    40  	m.stack = m.stack[:len(m.stack)-1]
    41  	m.last = time.Now()
    42  }
    43  
    44  func (m *metrics) dump(l *log.Logger) {
    45  	s := make(ndpairs, len(m.times))
    46  	k := 0
    47  	for n, d := range m.times {
    48  		s[k] = ndpair{
    49  			n: n,
    50  			d: d,
    51  		}
    52  		k++
    53  	}
    54  
    55  	sort.Sort(sort.Reverse(s))
    56  
    57  	var tot time.Duration
    58  	var buf bytes.Buffer
    59  	w := tabwriter.NewWriter(&buf, 0, 0, 1, ' ', tabwriter.AlignRight)
    60  	for _, nd := range s {
    61  		tot += nd.d
    62  		fmt.Fprintf(w, "\t%s:\t%v\t\n", nd.n, nd.d)
    63  	}
    64  	fmt.Fprintf(w, "\n\tTOTAL:\t%v\t\n", tot)
    65  	w.Flush()
    66  
    67  	l.Println("\nSolver wall times by segment:")
    68  	l.Println((&buf).String())
    69  }
    70  
    71  type ndpair struct {
    72  	n string
    73  	d time.Duration
    74  }
    75  
    76  type ndpairs []ndpair
    77  
    78  func (s ndpairs) Less(i, j int) bool { return s[i].d < s[j].d }
    79  func (s ndpairs) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    80  func (s ndpairs) Len() int           { return len(s) }