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

huangapple go评论85阅读模式
英文:

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

问题

我有两个使用for循环和递归的golang算法。我如何知道这两个算法消耗的速度和内存容量?

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)
    }
}
英文:

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&gt;=0; i--{
		fmt.Println(&quot;ForLoop = &quot;,i)
	}

}
func recursive(a int) int {
	if(a&lt;=0){
		return 0
	}else{
		fmt.Println(&quot;Recursive = &quot;,a)
		return recursive(a-1)
	}
}

答案1

得分: 1

首先,编写两个基准测试函数,一个用于调用每个算法。可以参考Marco Franssen的"在Go中测试和基准测试你的代码"中的示例。

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

其次,安装VSCode扩展Go Profiling,你将能够直接从你的IDE启动pprof:

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

然后,你可以比较每个函数所花费的时间。

注意:更好的pprof集成将在下一个版本的vscode-go中推出

how to know the speed and memory capacity consumed of the algorithm with golang
(可能在vscode-go 0.29中推出,请查看发布说明

英文:

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 &lt; b.N ; i++ {
    forLoop(100)
  }
}
func BenchmarkRecursive(b *testing.B) {
  for i := 0 ; i &lt; b.N ; i++ {
    recursive(100)
  }
}

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

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

You can then compare the time spent in each function.

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

how to know the speed and memory capacity consumed of the algorithm with golang
(possibly for vscode-go 0.29: check the releases)

huangapple
  • 本文由 发表于 2021年10月27日 09:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69731741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定