I need to verify how much memory a specific function consumes during execution, and make sure that it stays under a specific limit.
Ideally I'd like to do this in a test or benchmark. As far as I can see the only way to do this is to create a separate test binary and use the BenchmarkResult
from
func Benchmark(f func(b *B)) BenchmarkResult
Is this the correct way to do this?
Actually it's very simple:
runtime.ReadMemStats(&m)
into m
f()
m2
m
and m2
For example:
var m1, m2 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m1)
f()
runtime.ReadMemStats(&m2)
fmt.Println("total:", m2.TotalAlloc - m1.TotalAlloc)
fmt.Println("mallocs:", m2.Mallocs - m1.Mallocs)
That's not really how you use the testing
package. Just create a file called something_test.go
and write a function called func BenchmarkSomething(b *testing.B)
and you're good to go.
The documentation of the testing package goes into a lot more detail, but basically after you write your _test.go
files, you just run them, enable benchmarks, and specific to your question, turn on -benchmem
:
go test -bench=. -benchmem
That should give you what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With