Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preallocate p.stacks() before calling runtime.GoroutineProfile() #11

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion fgprof.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func Start(w io.Writer, format Format) func() error {
ticker := time.NewTicker(time.Second / hz)
stopCh := make(chan struct{})

prof := &profiler{}
prof := newProfiler()
stackCounts := stackCounter{}

go func() {
Expand Down Expand Up @@ -50,6 +50,16 @@ type profiler struct {
selfFrame *runtime.Frame
}

// newProfiler returns a new profiler with a pre-allocated stacks field. This
// is slightly faster than discovering its size during the first
// GoroutineProfile() call.
func newProfiler() *profiler {
n := runtime.NumGoroutine()
return &profiler{
stacks: make([]runtime.StackRecord, int(float64(n)*1.1)),
}
}

// GoroutineProfile returns the stacks of all goroutines currently managed by
// the scheduler. This includes both goroutines that are currently running
// (On-CPU), as well as waiting (Off-CPU).
Expand Down
11 changes: 7 additions & 4 deletions fgprof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fgprof
import (
"bytes"
"fmt"
"runtime"
"strings"
"testing"
"time"
Expand All @@ -26,7 +27,7 @@ func TestStart(t *testing.T) {
}

func BenchmarkProfiler(b *testing.B) {
prof := &profiler{}
prof := newProfiler()
for i := 0; i < b.N; i++ {
prof.GoroutineProfile()
}
Expand All @@ -38,8 +39,7 @@ func BenchmarkProfilerGoroutines(b *testing.B) {
name := fmt.Sprintf("%d goroutines", g)

b.Run(name, func(b *testing.B) {
prof := &profiler{}
initalRoutines := len(prof.GoroutineProfile())
initalRoutines := runtime.NumGoroutine()

readyCh := make(chan struct{})
stopCh := make(chan struct{})
Expand All @@ -51,6 +51,9 @@ func BenchmarkProfilerGoroutines(b *testing.B) {
<-readyCh
}

// allocate profiler after some goroutines has been generated
prof := newProfiler()

b.ResetTimer()
for i := 0; i < b.N; i++ {
stacks := prof.GoroutineProfile()
Expand Down Expand Up @@ -78,7 +81,7 @@ func BenchmarkProfilerGoroutines(b *testing.B) {
}

func BenchmarkStackCounter(b *testing.B) {
prof := &profiler{}
prof := newProfiler()
stacks := prof.GoroutineProfile()
sc := stackCounter{}
b.ResetTimer()
Expand Down