當時候需要去計算一段代碼或一個程序所消耗時間的時候,就需要進行統計時間,用程序去計算某一段代碼的執行所需要的時間遠比用眼睛直接去看程序運行時間高很多。
go語言中的time包中提供了函數來提供計算消耗時間,具體的使用方式如下案例所示:
bT := time.Now() // 開始時間
eT := time.Since(bT) // 從開始到當前所消耗的時間
fmt.Println("Run time: ", eT)
1.朴素方法
在函數起始位置計算當前時間,在函數結束位置算出耗時。
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) }
編譯運行輸出:
time cost = 350ns
count = 5050
2.簡潔方法
計算當前時間與計算耗時放在兩處,難免顯得丑陋,且不易閱讀。如果有多個函數需要統計耗時,那么多處書寫重復的兩行代碼會造成代碼冗余。由於 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()函數調用。不過相比於函數封裝帶來的便利與代碼美觀,新增的耗時是微不足道可以接受的。
3.優雅方法
每次調用耗時統計函數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
轉:https://cloud.tencent.com/developer/article/1447903