stopwatch

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2021 License: BSD-3-Clause Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

stopwatch

This package offers a nice solution to take some measurements of the various states of your application. It is a non high-resolution timer that is designed to be fast giving you an accurate picture of how long your code paths are taking.

BuildStatus Go Report Card GoDoc

Usage
package main

import (
	"encoding/json"
	"fmt"
	"github.com/sendgrid/stopwatch"
	"time"
)

func main() {

	// Create a new StopWatch that starts off counting
	sw := stopwatch.New(0, true)

	// Optionally, format that time.Duration how you need it
	// sw.SetFormatter(func(duration time.Duration) string {
	// 	return fmt.Sprintf("%.3f", (duration.Seconds()*1000.0)/1000.0)
	// })

	// Take measurement of various states
	sw.Lap("Create File")

	// Simulate some time by sleeping
	time.Sleep(time.Millisecond * 300)
	sw.Lap("Edit File")

	time.Sleep(time.Second * 2)
	sw.Lap("Save File")

	time.Sleep(time.Second * 3)
	sw.Lap("Upload File")

	// Take a measurement with some additional metadata
	time.Sleep(time.Millisecond * 20)
	sw.LapWithData("Delete File", map[string]interface{}{
		"filename": "word.doc",
		"size":     "1024",
	})

	// Stop the timer
	sw.Stop()

	// Marshal to json
	if b, err := json.Marshal(sw); err == nil {
		fmt.Println(string(b))
	}
}

You can also use stopwatch inside different goroutines like so,

	// Create a new StopWatch that starts off counting
	sw := New(0, true)

	// Optionally, format that time.Duration how you need it
	sw.SetFormatter(func(duration time.Duration) string {
		return fmt.Sprintf("%.1f", duration.Seconds())
	})

	// Take measurement of various states
	sw.Lap("Create File")

	var wg sync.WaitGroup

	wg.Add(2)
	go func() {
		defer wg.Done()
		for i := 0; i < 2; i++ {
			time.Sleep(time.Millisecond * 200)
			task := fmt.Sprintf("task %d", i)
			sw.Lap(task)
		}
	}()

	go func() {
		defer wg.Done()
		time.Sleep(time.Second * 1)
		task := "task A"
		sw.LapWithData(task, map[string]interface{}{
			"filename": "word.doc",
		})
	}()

	// Simulate some time by sleeping
	time.Sleep(time.Second * 1)
	sw.Lap("Upload File")

	// Stop the timer
	wg.Wait()
	sw.Stop()

	// Marshal to json
	if b, err := json.Marshal(sw); err == nil {
		fmt.Println(string(b))
	}

	// Output:
	// [{"state":"Create File","time":"0.0"},{"state":"task 0","time":"0.2"},{"state":"task 1","time":"0.2"},{"state":"Upload File","time":"0.6"},{"state":"task A","time":"0.0","filename":"word.doc"}]

Sample Output in Json format
[
    {
        "state": "Create File",
        "time": "1.341"
    },
    {
        "state": "Edit File",
        "time": "300.48635"
    },
    {
        "state": "Save File",
        "time": "2.001098212"
    },
    {
        "state": "Upload File",
        "time": "3.000983896"
    },
    {
        "state": "Delete File",
        "time": "20.724059",
        "filename": "word.doc",
        "size": "1024"
    }
]

Documentation

Index

Examples

Constants

View Source
const VERSION = "1.0.0"

VERSION represents the version of this library

Variables

This section is empty.

Functions

This section is empty.

Types

type FormattingMode

type FormattingMode string
const (
	// FormattingModeJsonArray formats Stopwatch to the form of an array of laps [{},{},...]
	FormattingModeJsonArray FormattingMode = "JSON_ARRAY"
	// FormattingModeJsonSimpleObject formats Stopwatch to the form object with property-per-lap {"Lap1":"10ms", "Lap2":"20ms"}
	// It's compatitable with ELK. Does not support additional lap data
	FormattingModeJsonSimpleObject FormattingMode = "JSON_OBJECT"
)

type Lap

type Lap struct {
	// contains filtered or unexported fields
}

Lap represents a split time from the stopwatch

func (Lap) String

func (l Lap) String() string

type Stopwatch

type Stopwatch struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Stopwatch is a non high-resolution timer for recording elapsed time deltas to give you some insight into how long things take for your app

Example (MultiThread)
// Create a new StopWatch that starts off counting
sw := New(0, true)

// Optionally, format that time.Duration how you need it
sw.SetFormatter(func(duration time.Duration) string {
	return fmt.Sprintf("%.0f", duration.Seconds())
})

// Take measurement of various states
sw.Lap("Create File")

var wg sync.WaitGroup

wg.Add(2)
go func() {
	defer wg.Done()
	for i := 0; i < 2; i++ {
		task := fmt.Sprintf("task %d", i)
		sw.Lap(task)
	}
}()

go func() {
	defer wg.Done()
	task := "task A"
	sw.LapWithData(task, map[string]interface{}{
		"filename": "word.doc",
	})
}()

// Simulate some time by sleeping
sw.Lap("Upload File")

// Stop the timer
wg.Wait()
sw.Stop()

laps := sw.Laps()
sorted := make([]string, 0, len(laps))
for _, lap := range laps {
	sorted = append(sorted, lap.String())
}
sort.Strings(sorted)
for _, lap := range sorted {
	fmt.Println(lap)
}
Output:
{"state":"Create File", "time":"0"}
{"state":"Upload File", "time":"0"}
{"state":"task 0", "time":"0"}
{"state":"task 1", "time":"0"}
{"state":"task A", "time":"0", "filename":"word.doc"}
Example (SingleThread)
// Create a new StopWatch that starts off counting
sw := New(0, true)

// Optionally, format that time.Duration how you need it
sw.SetFormatter(func(duration time.Duration) string {
	return fmt.Sprintf("%.0f", duration.Seconds())
})

// Take measurement of various states
sw.Lap("Create File")
sw.Lap("Edit File")
sw.Lap("Upload File")
// Take a measurement with some additional metadata
sw.LapWithData("Delete File", map[string]interface{}{
	"filename": "word.doc",
})

// Stop the timer
sw.Stop()

// Marshal to json
if b, err := json.Marshal(sw); err == nil {
	fmt.Println(string(b))
}
Output:
[{"state":"Create File","time":"0"},{"state":"Edit File","time":"0"},{"state":"Upload File","time":"0"},{"state":"Delete File","time":"0","filename":"word.doc"}]

func New

func New(offset time.Duration, active bool) *Stopwatch

New creates a new stopwatch with starting time offset by a user defined value. Negative offsets result in a countdown prior to the start of the stopwatch.

func (*Stopwatch) ElapsedTime

func (s *Stopwatch) ElapsedTime() time.Duration

ElapsedTime is the time the stopwatch has been active

func (*Stopwatch) Lap

func (s *Stopwatch) Lap(state string) Lap

Lap starts a new lap, and returns the length of the previous one.

func (*Stopwatch) LapTime

func (s *Stopwatch) LapTime() time.Duration

LapTime is the time since the start of the lap

func (*Stopwatch) LapWithData

func (s *Stopwatch) LapWithData(state string, data map[string]interface{}) Lap

LapWithData starts a new lap, and returns the length of the previous one allowing the user to pass in additional metadata to be recorded.

func (*Stopwatch) Laps

func (s *Stopwatch) Laps() []Lap

Laps returns a slice of completed lap times

func (*Stopwatch) MarshalJSON

func (s *Stopwatch) MarshalJSON() ([]byte, error)

MarshalJSON converts into a slice of bytes

func (*Stopwatch) Reset

func (s *Stopwatch) Reset(offset time.Duration, active bool)

Reset allows the re-use of a Stopwatch instead of creating a new one.

func (*Stopwatch) SetFormatter

func (s *Stopwatch) SetFormatter(formatter func(time.Duration) string)

SetFormatter takes a function that converts time.Duration into a string

func (*Stopwatch) SetFormattingMode

func (s *Stopwatch) SetFormattingMode(newMode FormattingMode)

Laps returns a slice of completed lap times

func (*Stopwatch) Start

func (s *Stopwatch) Start()

Start intiates, or resumes the counting up process

func (*Stopwatch) Stop

func (s *Stopwatch) Stop()

Stop makes the stopwatch stop counting up

func (*Stopwatch) String

func (s *Stopwatch) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL