Hamka Satria
Hamka Satria

Reputation: 19

how to know the speed and memory capacity consumed of the algorithm with golang

I have 2 golang algorithms, which use a for loop and recursive. how do i know the speed and memory capacity consumed of my two algorithms ?

func forLoop(a int){
    for i:=a; i>=0; i--{
        fmt.Println("ForLoop = ",i)
    }

}
func recursive(a int) int {
    if(a<=0){
        return 0
    }else{
        fmt.Println("Recursive = ",a)
        return recursive(a-1)
    }
}

Upvotes: -1

Views: 456

Answers (1)

VonC
VonC

Reputation: 1323125

First, write two Benchmark test functions, one for calling each algorithm.
See an example in "Test and benchmark your code in go" from Marco Franssen.

// main_test.go
func BenchmarkLoop(b *testing.B) {
  for i := 0 ; i < b.N ; i++ {
    forLoop(100)
  }
}
func BenchmarkRecursive(b *testing.B) {
  for i := 0 ; i < b.N ; i++ {
    recursive(100)
  }
}

Second, install the VSCode extension Go Profiling, and you will be able to launch pprof directly from your IDE:

https://raw.githubusercontent.com/MaxM65dia/vscode-go-prof/master/media/preview.gif

You can then compare the time spent in each function.

Note: a better pprof integration is coming with the next version of vscode-go:

vscode go
(possibly for vscode-go 0.29: check the releases)

Upvotes: 1

Related Questions