felixge / fgprof

🚀 fgprof is a sampling Go profiler that allows you to analyze On-CPU as well as Off-CPU (e.g. I/O) time together.
MIT License
2.88k stars 96 forks source link

Replace fmt.Sscanf with strconv.Atoi for faster int conversion #7

Closed sabandi closed 4 years ago

sabandi commented 4 years ago

Ran a benchmark with this change and saw significant decrease(98.6%) in the runtime. Also added early return in else if block to fail early.

Test code:

func BenchmarkFmtSscanf(b *testing.B) {
    var seconds int
    for i := 0; i < b.N; i++ {
        _, _ = fmt.Sscanf("300", "%d", &seconds)
        _ = seconds

    }
}

func BenchmarkAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        seconds, _ := strconv.Atoi("-300")
        _ = seconds
    }
}

Test Results:

➜  go-code git:(master) ✗ go test -bench=. a_test.go
goos: darwin
goarch: amd64
BenchmarkFmtSscanf-8           2430686               486 ns/op
BenchmarkAtoi-8                    176275149                6.66 ns/op