衡量Golang代碼執行時間
實際開發中經常需要衡量代碼性能,包括代碼片段或業務函數。本文介紹如何衡量Golang代碼執行時間,既簡潔又實用。
1. 代碼片段執行時間
使用time.Now()
和time.Since()
可衡量代碼片段的執行時間:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("簡單衡量 Golang 代碼片段執行時間示例")
fmt.Println("")
start := time.Now()
//measuring the durration of the for loop
for index := 0; index < 10; index++ {
time.Sleep(500 * time.Millisecond)
}
elapsed := time.Since(start)
fmt.Printf("The `for` loop took %s", elapsed)
}
上面示例中循環迭代10次,每次睡眠500毫秒,模擬執行復雜任務。
輸出如下:
簡單衡量 Golang 代碼片段執行時間示例
The `for` loop took 5.000286s
循環10次,每次500毫秒,總共時間約5秒多。
2. 函數執行時間
爲了衡量函數執行時間,我們創建一個專門函數衡量執行時間,與業務代碼分離,增加複用性。
在執行任務開始時使用defer
,確保函數執行完畢之前調用衡量執行時間函數。
package main
import (
"fmt"
"time"
)
func timeMeasurement(start time.Time) {
elapsed := time.Since(start)
fmt.Printf("Execution time: %s", elapsed)
}
func workerFunction() {
fmt.Println("Running 'workerFunction' function")
for index := 0; index < 10; index++ {
time.Sleep(500 * time.Millisecond)
}
}
func main() {
fmt.Println("Function time measurement Golang Example")
fmt.Println("")
defer timeMeasurement(time.Now())
workerFunction()
}
當然defer timeMeasurement(time.Now())
也可以放在workerFunction
函數體開頭位置,爲了不侵入業務代碼,我們放在其被執行之前位置。輸出如下:
衡量Golang 函數執行時間示例
Running 'workerFunction' function
Execution time: 5.0032861s
3. 總結
本文介紹了Golang衡量執行時間的方法,包括代碼片段和函數的執行時間。主要使用defer關鍵字實現延遲機制,確保執行完成之前進計算執行時間。