9

Go 计算程序运行时间

 3 years ago
source link: https://studygolang.com/articles/32231
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Go 计算程序运行时间

小谷xg · 1天之前 · 81 次点击 · 预计阅读时间不到 1 分钟 · 不到1分钟之前 开始浏览    

1.计算代码块的运行时间

start := time.Now()
//some func or operation
cost := time.Since(start)
fmt.Printf("cost=[%s]",cost)
  • 其中time.Since()函数返回字符串类型,例如1h2m3s等,可能还有us等

2.计算函数的运行时间

func compute() {
    start := time.Now()
    defer func() {
        cost := time.Since(start)
        fmt.Println("cost=", cost)
    }()
    // some computation
}
  • 利用defer的作用,可以在函数开始的时候获取一个时间,使用time.Now()在函数结束的时候,获取程序从标记开始的时间段,可以得到函数运行的时间。

有疑问加站长微信联系(非本文作者)

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:1006366459


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK