英文:
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>=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)
}
}
答案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:
然后,你可以比较每个函数所花费的时间。
注意:更好的pprof集成将在下一个版本的vscode-go中推出:
(可能在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 < 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:
You can then compare the time spent in each function.
Note: a better pprof integration is coming with the next version of vscode-go:
(possibly for vscode-go 0.29: check the releases)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论