我想到了使用defer语句来测量 Go 中程序的运行时间:
func main() {
start := time.Now()
defer fmt.Println(fmt.Sprintf("The process took %s", time.Now().Sub(start)))
...
}
我认为这会产生正确的结果,但事实并非如此:
[09:36:55]pc@work:~/test$ go run ./main.go
Processed 209806/209806 TUF files
All records are inserted in the database.
Verifying records are inserted correctly...
Verified 209806/209806 TUF files
All records have been inserted and verified successfully.
The process took 600ns
[14:24:06]pc@work:~/test$
尽管该过程耗时 5 小时(从左侧的时间戳可以看出),但延迟fmt.Println()语句显示为 600 纳秒。我究竟做错了什么?
心有法竹
九州编程
相关分类