Determine the memory consumption

Asked

Viewed 79 times

2

Hello, I’m a beginner in Go and I’m having a hard time determining how much memory the Go code took to execute some code. I made the memory() function that even returns something, but I don’t know how it would be to bring the return I want, it would be like: the code needed 15MB to be executed, for example, would it have to do this? Thank you in advance!

package main

import (
    "fmt"
    "log"
    "runtime"
    "time"
)

func ack(m, n uint) uint {
    if m == 0 {
        return n + 1
    } else if n == 0 {
        return ack(m - 1, 1)
    } else {
        return ack(m - 1, ack(m, n - 1))
    }
}

func memory(){
    for {
        var m runtime.MemStats
        runtime.ReadMemStats(&m)
        log.Printf("\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", m.Alloc / 1024, m.TotalAlloc / 1024, m.Sys / 1024, m.NumGC)
        time.Sleep(5 * time.Second)
    }
}

func main() {

    var inicio = time.Now().UnixNano()
    fmt.Println(ack(1,2))
    var fim = time.Now().UnixNano()
    fmt.Println(fim - inicio)

    memory()

}
  • You need stack, heap, or time?

  • I need the total memory that was used to execute the code

1 answer

1

The question is old, but I think it’s always worth answering.

I suggest taking a look at the test package (https://golang.org/pkg/testing/) native of Go. There are several interesting functions for this kind of thing.

For your specific case, you would use the Benchmark test feature, which gives you information like memory allocation, as well as, of course, the Bench of your function.

To use benchmark in Go functionality, create a new file by following the format:

[file name]_test.go

In this file, import the test package and create a function in the following format:

*func Benchmark[function name](b testing. B) {}

It is crucial that the function begins with the term Benchmark because otherwise Go will not recognize this as a Benchmark function and will give error.

Follow an example with your code:

func ack(m, n uint) uint {
    if m == 0 {
        return n + 1
    } else if n == 0 {
        return ack(m-1, 1)
    } else {
        return ack(m-1, ack(m, n-1))
    }
}

func BenchmarkAck(b *testing.B) {
    ack(1, 2)
}

To run use the command: go test -Bench=. with the -benchmem flag to view memory allocation information etc:

go test -bench=. -benchmem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.