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

Time:10-27

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)
    }
}

CodePudding user response:

First, write two Benchmark test functions, one for calling each algorithm.
See an example in "https://raw.githubusercontent.com/MaxM65dia/vscode-go-prof/master/media/preview.gif

You can then compare the time spent in each function.

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

CodePudding user response:

Use time.Now().UnixNano() to calculate delta time:

func main() {
   t1 := time.Now().UnixNano()
   forLoop(100)
   recursive(100)
   t2 := time.Now().UnixNano()
   fmt.Print("cost ns",t2 - t1)
}
  • Related