github.com/biogo/biogo@v1.0.4/util/timing.go (about)

     1  // Copyright ©2011-2012 The bíogo Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  //
     5  // Derived from testing/benchmark.go Copyright 2009 The Go Authors
     6  // under the BSD license.
     7  
     8  package util
     9  
    10  import "time"
    11  
    12  type Timer struct {
    13  	nanoseconds time.Duration
    14  	start       time.Time
    15  	interval    time.Time
    16  }
    17  
    18  func NewTimer() (t *Timer) {
    19  	t = &Timer{}
    20  	t.Start()
    21  	return
    22  }
    23  
    24  // Start starts timing. This function is called automatically when a timer is created,
    25  // but it can also used to resume timing after a call to StopTimer.
    26  func (t *Timer) Start() { t.start = time.Now(); t.interval = t.start }
    27  
    28  // Stop stops timing. This can be used to pause the timer while performing complex
    29  // initialization that you don't want to measure.
    30  func (t *Timer) Stop() time.Duration {
    31  	if t.start.After(time.Time{}) {
    32  		t.nanoseconds += time.Now().Sub(t.start)
    33  	}
    34  	t.start = time.Time{}
    35  
    36  	return t.nanoseconds
    37  }
    38  
    39  // Reset stops the timer and sets the elapsed time to zero.
    40  func (t *Timer) Reset() {
    41  	t.start = time.Time{}
    42  	t.nanoseconds = 0
    43  }
    44  
    45  // Time returns the measured time.
    46  func (t *Timer) Time() time.Duration {
    47  	return t.nanoseconds
    48  }
    49  
    50  // Start and return a time interval.
    51  func (t *Timer) Interval() (l time.Duration) {
    52  	if t.start.After(time.Time{}) {
    53  		l = time.Now().Sub(t.interval)
    54  		t.interval = time.Now()
    55  	}
    56  
    57  	return
    58  }