code.vegaprotocol.io/vega@v0.79.0/core/metrics/timecounter.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package metrics
    17  
    18  import (
    19  	"time"
    20  )
    21  
    22  // TimeCounter holds a time.Time and a list of label values, hiding the start time from being accidentally
    23  // overwritten, and removing the need to duplicate the label values.
    24  type TimeCounter struct {
    25  	labelValues []string
    26  	start       time.Time
    27  }
    28  
    29  // NewTimeCounter returns a new TimeCounter, with the start time already recorded.
    30  func NewTimeCounter(labelValues ...string) *TimeCounter {
    31  	return &TimeCounter{
    32  		labelValues: labelValues,
    33  		start:       time.Now(),
    34  	}
    35  }
    36  
    37  /*
    38  EngineTimeCounterAdd is used to time a function.
    39  e.g.
    40  
    41  	func DoSomething() {
    42  		timer := metrics.NewTimeCounter("x", "y", "z")
    43  		// do something
    44  		timer.EngineTimeCounterAdd()
    45  	}
    46  */
    47  func (tc *TimeCounter) EngineTimeCounterAdd() {
    48  	// Check that the metric has been set up. (Testing does not use metrics.)
    49  	if engineTime == nil {
    50  		return
    51  	}
    52  	engineTime.WithLabelValues(tc.labelValues...).Add(time.Since(tc.start).Seconds())
    53  }