Golang 打印耗时统计

参考URL: https://cloud.tencent.com/developer/article/1447903

go语言中的time包中提供了函数来提供计算消耗时间

bT := time.Now()            // 开始时间
eT := time.Since(bT)      // 从开始到当前所消耗的时间
fmt.Println("Run time: ", eT)

普通demo

package main

import (
    "fmt"
    "time"
)

func sum(n int) int {
	startT := time.Now()		//计算当前时间
	
    total := 0
    for i:=1; i <= n; i++ {
        total += i
    }
	
	tc := time.Since(startT)	//计算耗时
	fmt.Printf("time cost = %v\n", tc)
    return total
}

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

利用defer的简洁方法

计算当前时间与计算耗时放在两处,难免显得丑陋,且不易阅读。如果有多个函数需要统计耗时,那么多处书写重复的两行代码会造成代码冗余。由于 Golang 提供了函数延时执行的功能,借助 defer ,我们可以通过函数封装的方式来避免代码冗余。

package main

import (
    "fmt"
    "time"
)

//@brief:耗时统计函数
func timeCost(start time.Time){
	tc:=time.Since(start)
	fmt.Printf("time cost = %v\n", tc)
}

func sum(n int) int {
	defer timeCost(time.Now())
    total := 0
    for i:=1; i <= n; i++ {
        total += i
    }
	
    return total
}

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

编译运行输出:

time cost = 1.574µs
count = 5050

通过输出可以看到sum()耗时增加了,因为增加了一次timeCost()函数调用。不过相比于函数封装带来的便利与代码美观,新增的耗时是微不足道可以接受的。

利用defer更优雅的方法

**每次调用耗时统计函数timeCost()都需要传入time.Now(),重复书写time.Now()**无疑造成了代码冗余。我们在上面的基础上,进行进一步的封装,实现如下。

package main

import (
    "fmt"
    "time"
)

//@brief:耗时统计函数
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)
}

编译运行输出:

time cost = 1.204µs
count = 5050

原理:利用defer中函数在声明的时候就确定参数这一特点,来实现函数执行启动时间的传入,然后函数执行结束前,再执行defer,在defer里面读取到整个函数执行时间

纳秒级耗时统计

上面方法,会自动转换耗时,方便阅读。有些场景我们需要精确的纳秒耗时。

如下示例,我们使用 time.Now().UnixNano() 获取ns,然后相减获取。


package main
 
import (
    "time"
    "fmt"
)
 
func main() {
 
    startTime := time.Now().UnixNano()
 
    /* 程序主体 */
 
    endTime := time.Now().UnixNano()
    nanoSeconds:= float64(endTime - startTime)  // ns
    
	fmt.Printf("cost time : %v ns\n", nanoSeconds)
	fmt.Printf("cost time(ms) :%v;\n",nanoSeconds / 1e6)
	fmt.Printf("cost time(s) :%v;\n",nanoSeconds / 1e9)

}

time.Now().UnixNano()

UnixNano返回t作为Unix时间,即从January 1, 1970 UTC.经过的纳秒数。