Skip to content

Commit

Permalink
Mutexes added to timers, added NewTimer
Browse files Browse the repository at this point in the history
This is the preferred way to allocate a timer now
  • Loading branch information
markdicksonjr committed Jun 2, 2019
1 parent fc7a045 commit 11085fc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ A sample integration of Batch and and XML Reader is provided in ./xml/sample.

### Simple Timer

To create a timer, call `NewTimer()` (optionally, you can set timer.NoOp to disable the timer processing (if not debugging, etc).

To use the timer, call `timer.Start("SomeTitle")` where SomeTitle describes the operation that is
being timed. When complete, call `timer.Stop("SomeTitle")` where SomeTitle is the same operation
description used for the corresponding timer Start.
Expand Down
39 changes: 25 additions & 14 deletions timer.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
package work

import "time"
import (
"sync"
"time"
)

type Timer struct {
NoOp bool
startTimes map[string]*time.Time
totals map[string]int64
counts map[string]int
mapMutex *sync.Mutex
}

func NewTimer() *Timer {
return &Timer{
NoOp: false,
startTimes: make(map[string]*time.Time),
totals: make(map[string]int64),
counts: make(map[string]int),
mapMutex: &sync.Mutex{},
}
}

type TimerRecord struct {
Expand All @@ -20,47 +34,43 @@ func (t *Timer) Start(label string) {
return
}

if t.startTimes == nil {
t.startTimes = make(map[string]*time.Time)
}

if t.totals == nil {
t.totals = make(map[string]int64)
}

if t.counts == nil {
t.counts = make(map[string]int)
}

t.mapMutex.Lock()
now := time.Now()
t.startTimes[label] = &now
t.mapMutex.Unlock()
}

func (t *Timer) Stop(label string) {
if t.NoOp {
return
}

t.mapMutex.Lock()
start := t.startTimes[label]
if start != nil {
timing := time.Now().Sub(*start).Nanoseconds()
t.totals[label] += timing
t.counts[label]++
}
t.mapMutex.Unlock()
}

func (t *Timer) GetTimingsForLabel(label string) TimerRecord {
return TimerRecord{
t.mapMutex.Lock()
result := TimerRecord{
Count: t.counts[label],
TotalTime: t.totals[label],
Label: label,
}
t.mapMutex.Unlock()
return result
}

func (t *Timer) GetTimings() []TimerRecord {
var result []TimerRecord

if !t.NoOp {
t.mapMutex.Lock()
for label, timing := range t.totals {
count := t.counts[label]

Expand All @@ -70,6 +80,7 @@ func (t *Timer) GetTimings() []TimerRecord {
Label: label,
})
}
t.mapMutex.Unlock()
}

return result
Expand Down

0 comments on commit 11085fc

Please sign in to comment.