我遇到了一个问题,其中time.Since()产生0。谁能突然解释为什么会发生这种情况?我正在尝试衡量Web服务器调用的执行时间。
func handle(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
start := time.Now()
f(w, r)
elapsed := time.Since(start)
log.Printf("took %s", elapsed)
}
}
它产生此输出,有时会给出“ took 0s” 。我在这里想念东西吗?
2019/01/24 23:28:45 /hello
2019/01/24 23:28:45 took 1.9878ms
2019/01/24 23:28:45 /hello
2019/01/24 23:28:45 took 998.6µs
2019/01/24 23:28:46 /hello
2019/01/24 23:28:46 took 1.0007ms
2019/01/24 23:28:46 /hello
2019/01/24 23:28:46 took 0s
2019/01/24 23:28:46 /hello
2019/01/24 23:28:46 took 0s
2019/01/24 23:28:46 /hello
2019/01/24 23:28:46 took 998.8µs
2019/01/24 23:28:47 /hello
2019/01/24 23:28:47 took 0s
2019/01/24 23:28:47 /hello
2019/01/24 23:28:47 took 0s
答案 0 :(得分:4)
我用一个简单的函数复制了您的场景,该函数的执行时间为微秒 (µs)。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println("Start")
for i := 0; i < 10; i++ {
start := time.Now()
var i = rand.Float64() * 100
time.Sleep(time.Duration(i) * time.Microsecond)
elapsed := time.Since(start)
fmt.Printf("took %s", elapsed)
fmt.Println()
}
}
但是我没有得到 0s
输出:
Start
took 60µs
took 94µs
took 66µs
took 43µs
took 42µs
took 68µs
took 6µs
took 15µs
took 9µs
took 30µs