1 Conventional writing
package main
import (
"fmt"
"time"
)
func main() {
bT := time.Now() // 开始时间
time.Sleep(5*time.Second)
eT := time.Since(bT) // 从开始到当前所消耗的时间
fmt.Println("Run time: ", eT)
}
operation result:
Run time: 5.001531s
2 original way
Calculate the current time at the beginning of the function, and calculate the elapsed time at the end of the function.
package main
import (
"fmt"
"time"
)
func sum(n int) int {
var total 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)
}
operation result:
time cost = 250ns
count = 5050
3 concise method
The calculation of the current time and the calculation time are placed in two places, which is inevitably ugly and difficult to read. If there are multiple functions that need time-consuming statistics, writing two lines of code that are repeated in multiple places will cause code redundancy. Since Golang provides the function of delayed execution of functions, with the help of defer, code redundancy can be avoided through function encapsulation.
package main
import (
"fmt"
"time"
)
//耗时统计函数
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)
}
operation result:
time cost = 333ns
count = 5050
It can be seen from the output that the time consumption of sum() has increased, because a timeCost() function call has been added. However, compared to the convenience and beautiful code brought by function encapsulation, the additional time-consuming is negligible and acceptable.
4 elegant methods
Every time the time-consuming statistics function timeCost() is called, it needs to be passed in time.Now()
. Repeated writing time.Now()
will undoubtedly cause code redundancy. On the basis of the above, further encapsulation is carried out as follows:
package main
import (
"fmt"
"time"
)
//耗时统计函数
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)
}
operation result:
time cost = 1.204µs
count = 5050