S
S
starosta462019-06-21 08:51:11
go
starosta46, 2019-06-21 08:51:11

Is it possible to benchmark functions from packages in golang?

Hello. There is a models file with the following code:

package api

import "encoding/json"

type Awesome struct {
  Id        string  `json:"id"`
  Message   string  `json:"message"`
  Score     float64 `json:"score"`
  Confirmed bool    `json:"confirmed"`
}

func NewAwesome(id string, message string, score float64, confirmed bool) *Awesome {
  return &Awesome{
    id,
    message,
    score,
    confirmed,
  }
}

func(a *Awesome) ToJSON() ([]byte, error) {
  return json.Marshal(a)
}

I want to make a benchmark of the ToJSON function. For this, in the same directory there is a models_test file with the following code:
package api

import "testing"



func BenchmarkAwesomeToJSON(b *testing.B) {
  for i := 0; i < b.N; i++ {
    awesome := NewAwesome("123456789", "Total awesomeness", 9.99, true)
    awesome.ToJSON()
  }
}

However, when I run the benchmark (go test -bench . models_test.go ), I get the following error:
./models_test.go:9:14: undefined: NewAwesome
If we transfer the function to a test file, then everything works. Is it possible to test functions from other files and from other packages? And, if so, what needs to be done to achieve this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2019-06-21
@starosta46

Of course you can, but you specify only one file in the project, run it through go test -bench .and it will work.

$ go test -bench . 
goos: darwin
goarch: amd64
pkg: api
BenchmarkAwesomeToJSON-8         3000000               470 ns/op
PASS
ok      api    1.895s

you can specify only the files you need go test -bench . test_test.go test.go, but it's easier without them.
Also, the benchmark is not quite correctly designed, in your case, not only the performance of json.Marshal () is measured, but also the performance of creating an object.
It would be correct to do this:
func BenchmarkAwesomeToJSON(b *testing.B) {
  awesome := NewAwesome("123456789", "Total awesomeness", 9.99, true)

  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    awesome.ToJSON()
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question