doupafu6980 2017-08-19 00:34
浏览 155
已采纳

有没有一种有效的方法来计算golang中的执行时间?

I'm looking for the best way to calculate execution time in go.

func main() {
    start := time.Now()

    time.Sleep(time.Second * 2)

    //something doing here

    elapsed := time.Since(start)
    fmt.Printf("page took %s", elapsed)
}

The code above works fine.

But when I use templates, I have to write it again for each template function.

Is there an efficient way to calculating execution time including templates ?

  • 写回答

4条回答 默认 最新

  • douweng5420 2017-08-19 01:02
    关注

    If you are timing an entire function, then you can use defer to eliminate some of the repetitive code.

    func elapsed(what string) func() {
        start := time.Now()
        return func() {
            fmt.Printf("%s took %v
    ", what, time.Since(start))
        }
    }
    
    func main() {
        defer elapsed("page")()
        time.Sleep(time.Second * 2)
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 需求DC-DC降压电路
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?
  • ¥15 es 7.17.20版本生成时间戳
  • ¥15 wpf dategrid表头排序图标自定义
  • ¥15 xshell无法连接提示ssh服务器拒绝密码