衡量 golang 函数性能的主要指标有:执行时间(衡量函数运行所需时间)、内存分配(衡量函数分配的内存数量)、cpu 使用率(衡量函数使用的 cpu 时间数量)和 goroutine 数量(衡量函数创建的 goroutine 数量)。

衡量 Golang 函数性能时的常见指标
在 Golang 中衡量函数性能时,有几个常见的指标需要考虑:
1. 执行时间
这是衡量函数运行所需时间的指标。可以使用以下代码获取执行时间:
import "time"
func Sum(a, b int) int {
start := time.Now()
result := a + b
elapsed := time.Since(start)
fmt.Println("Execution time:", elapsed)
return result
}
2. 内存分配
这是衡量函数在执行期间分配的内存数量的指标。可以使用以下代码获取内存分配:
import "runtime"
func Sum(a, b int) int {
memBefore := runtime.MemStats.TotalAlloc
result := a + b
memAfter := runtime.MemStats.TotalAlloc
memAllocated := memAfter - memBefore
fmt.Println("Memory allocated:", memAllocated)
return result
}
3. CPU 使用率
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
这是衡量函数在执行期间使用的 CPU 时间数量的指标。可以使用以下代码获取 CPU 使用率:
import (
"runtime"
"time"
)
func Sum(a, b int) int {
cpuBefore := runtime.NumCPU()
start := time.Now()
result := a + b
elapsed := time.Since(start)
cpuAfter := runtime.NumCPU()
cpuUsed := cpuAfter - cpuBefore
fmt.Println("CPU used:", cpuUsed)
return result
}
4. Goroutine 数量
这是衡量函数在执行期间创建的 goroutine 数量的指标。可以使用以下代码获取 goroutine 数量:
import "runtime"
func Sum(a, b int) int {
goCountBefore := runtime.NumGoroutine()
result := a + b
goCountAfter := runtime.NumGoroutine()
goroutinesCreated := goCountAfter - goCountBefore
fmt.Println("Goroutines created:", goroutinesCreated)
return result
}
实战案例:
以下是一个基准测试代码的示例,它使用这些指标来比较两个不同实现的加法函数的性能:
package main
import (
"fmt"
"runtime"
"strconv"
"testing"
"time"
)
func Sum1(a, b int) int {
return a + b
}
func Sum2(a, b int) int {
c := strconv.Itoa(a) + strconv.Itoa(b)
i, err := strconv.Atoi(c)
if err != nil {
panic(err)
}
return i
}
func main() {
numRuns := 10000000
start := time.Now()
for i := 0; i <p>以上代码演示了如何使用这些指标来比较不同函数实现的性能。</p>
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










