~juju-qa/ubuntu/yakkety/juju/2.0-rc3-again

« back to all changes in this revision

Viewing changes to src/launchpad.net/juju-core/utils/timeit.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-04-24 22:34:47 UTC
  • Revision ID: package-import@ubuntu.com-20130424223447-f0qdji7ubnyo0s71
Tags: upstream-1.10.0.1
ImportĀ upstreamĀ versionĀ 1.10.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package utils
 
2
 
 
3
import (
 
4
        "fmt"
 
5
        "os"
 
6
        "time"
 
7
)
 
8
 
 
9
type timer struct {
 
10
        action     string
 
11
        start      time.Time
 
12
        depth      int
 
13
        duration   time.Duration
 
14
        subActions []*timer
 
15
}
 
16
 
 
17
func (t *timer) String() string {
 
18
        this := fmt.Sprintf("%.3fs %*s%s\n", t.duration.Seconds(), t.depth, "", t.action)
 
19
        for _, sub := range t.subActions {
 
20
                this += sub.String()
 
21
        }
 
22
        return this
 
23
}
 
24
 
 
25
var stack []*timer
 
26
 
 
27
// Start a timer, used for tracking time spent.
 
28
// Generally used with either defer, as in:
 
29
//  defer utils.Timeit("my func")()
 
30
// Which will track how much time is spent in your function. Or
 
31
// if you want to track the time spent in a function you are calling
 
32
// then you would use:
 
33
//  toc := utils.Timeit("anotherFunc()")
 
34
//  anotherFunc()
 
35
//  toc()
 
36
// This tracks nested calls by indenting the output, and will print out the
 
37
// full stack of timing when we reach the top of the stack.
 
38
func Timeit(action string) func() {
 
39
        cur := &timer{action: action, start: time.Now(), depth: len(stack)}
 
40
        if len(stack) != 0 {
 
41
                tip := stack[len(stack)-1]
 
42
                tip.subActions = append(tip.subActions, cur)
 
43
        }
 
44
        stack = append(stack, cur)
 
45
        return func() {
 
46
                cur.duration = time.Since(cur.start)
 
47
                if cur == stack[0] {
 
48
                        fmt.Fprint(os.Stderr, cur)
 
49
                        stack = nil
 
50
                } else {
 
51
                        stack = stack[0 : len(stack)-1]
 
52
                }
 
53
        }
 
54
}