1. Home
  2. Docs
  3. golang
  4. 代码优化
  5. 性能优化

性能优化

v1-如何统计程序运行的时间?

package main

import (
    "fmt"
    "time"
)

// 统计一个程序运行的时间
func main() {
    start := time.Now()

    // other more flow code
    time.Sleep(1000 * 3 * time.Millisecond)

    fmt.Printf("%.2fs run time\n", time.Since(start).Seconds())
}

v2-如何统计程序运行的时间? 优雅方案

package main

import (
    "fmt"
    "time"
)

// timeCost 耗时统计
func timeCost() func() {
    start := time.Now()
    return func() {
        tc:=time.Since(start)
        fmt.Printf("time cost = %v\n", tc)
    }
}

func sum(n int) int {
    defer timeCost()()      // 注意,是对 timeCost() 返回的函数进行延迟调用,因此需要加两对小括号
    total := 0
    for i:=1; i <= n; i++ {
        total += i
    }
    return total
}

func main() {
    count := sum(100)
    fmt.Printf("count = %v\n", count)
}

相关资料

Go 函数耗时统计

Was this article helpful to you? Yes No

How can we help?