dpyln64620 2019-04-23 04:58
浏览 301
已采纳

为什么time.Since(start).Seconds()总是返回0?

I am on the first chapter The Go Programming Language (Addison-Wesley Professional Computing Series) and the 3rd exercise in the book asks me to measure code performance using time.

So, I came up with the following code.

start := time.Now()
var s, sep string
for i := 1; i < len(os.Args); i++ {
    s += sep + os.Args[i]
    sep = " "
}
fmt.Print(s)
fmt.Printf("
Took %.2fs 
", time.Since(start).Seconds())
fmt.Println("------------------------------------------------")
start2 := time.Now()
fmt.Print(strings.Join(os.Args[1:], " "))
fmt.Printf("
Took %.2fs", time.Since(start2).Seconds())

When I ran this code on Windows and Mac, it always return 0.00 second. I added a pause in my code to check whether it's correct and it seems fine. What I don't understand is why it always returns 0.0.

  • 写回答

1条回答 默认 最新

  • duangekui7451 2019-04-23 05:33
    关注

    There is very little code between your start times and the time.Since() calls, in the first example just a few string concatenations and an fmt.Print() call, in the second example just a single fmt.Print() call. These are executed by your computer very fast.

    So fast, that the result is most likely less than a millisecond. And you print the elapsed time using the %.2f verb, which rounds the seconds to 2 fraction digits. Which means if the elapsed time is less than 0.005 sec, it will be rounded to 0. This is why you see 0.00s printed.

    If you change the format to %0.12f, you will see something like:

    Took 0.000027348000s 
    Took 0.000003772000s
    

    Also note that the time.Duration value returned by time.Since() implements fmt.Stringer, and it "formats" itself intelligently to a unit that is more meaningful. So you may print it as-is.

    For example if you print it like this:

    fmt.Println("Took", time.Since(start))
    fmt.Println("Took", time.Since(start2))
    

    You will see an output something like this:

    Took 18.608µs
    Took 2.873µs
    

    Also note that if you want to measure the performance of some code, you should use Go's built-in testing and benchmarking facilities, namely the testing package. For details, see Order of the code and performance.

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

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题