douxian3170 2015-05-07 10:18
浏览 17
已采纳

Golang获取执行动作的流程时间

I really interested in how much time is spending time to do this action. Does anybody have any best idea? or any library. I did with simple way, but it seems as wrong way. Because I did have more experience with workin on go

My have that code:

package main

import (
    "fmt"
    "time"
)

func main() {
    var d int = 0
    var beginTime = time.Now()
    for i := 0; i < 100000; i++ {

        for c := 0; c < 100; c++ {
            d = 1
        }
    }
    var endTime = time.Now()
    fmt.Println(beginTime, endTime)
    fmt.Println(time.Since(beginTime))
    fmt.Println(d)
}
  • 写回答

1条回答 默认 最新

  • dtml3340 2015-05-07 10:44
    关注

    Use the built-in Benchmarks.

    A sample benchmark function looks like this:

    func BenchmarkHello(b *testing.B) {
        for i := 0; i < b.N; i++ {
            fmt.Sprintf("hello")
        }
    }
    

    The benchmark function must run the target code b.N times. During benchark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output

    BenchmarkHello    10000000    282 ns/op
    

    means that the loop ran 10000000 times at a speed of 282 ns per loop.

    EDIT: If you want to measure time of doing something at runtime, and not in your tests, your way looks fine to me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM