我正在嘗試測量funcWithUnpredictiveExecutionTime函數的執(zhí)行時間。func measureTime(expectedMs float64) (ok bool) { t1 := time.Now() funcWithUnpredictiveExecutionTime() t2 := time.Now() diff := t2.Sub(t1)當funcWithUnpredictiveExecutionTime工作速度比我預期的要快時,測量就很好了 。但是,如果它的工作速度比expectedMs 預期的毫秒數還慢,則測量不會立即停止。當funcWithUnpredictiveExecutionTime工作時間比expectedMs不等待funcWithUnpredictiveExecutionTime完成時間更長時,是否可以停止時間測量?換句話說,無論如何measureTime(200)都應該200 ms以好的或壞的結果返回。我想我應該使用頻道,然后以某種方式取消等待頻道。但是具體怎么做呢?完整代碼:package mainimport ( "fmt" "math/rand" "time")// random number between min and maxfunc random(min, max int) int { rand.Seed(time.Now().Unix()) return rand.Intn(max-min) + min}// sleeps for a random milliseconds amount between 200 and 1000func funcWithUnpredictiveExecutionTime() { millisToSleep := random(200, 1000) fmt.Println(fmt.Sprintf("Sleeping for %d milliseconds", millisToSleep)) time.Sleep(time.Millisecond * time.Duration(millisToSleep))}// measures execution time of a function funcWithUnpredictiveExecutionTime// if expectedMs < actual execution time, it's ok.// if expectedMs milliseconds passed and funcWithUnpredictiveExecutionTime// still did not finish execution it should return// without waiting for funcWithUnpredictiveExecutionTimefunc measureTime(expectedMs float64) (ok bool) { t1 := time.Now() funcWithUnpredictiveExecutionTime() t2 := time.Now() diff := t2.Sub(t1) actualMs := diff.Seconds() * 1000 ok = actualMs < expectedMs fmt.Println(actualMs) return}// prints results: Ok or too latefunc printTimeResults(ok bool) { if ok { fmt.Println("Ok") } else { fmt.Println("Too late") }}func main() { printTimeResults(measureTime(200)) // expect it to finish in 200 ms anyway printTimeResults(measureTime(1000)) // expect it to finish in 1000 ms anyway}輸出:Sleeping for 422 milliseconds424.11895200000004Too lateSleeping for 422 milliseconds425.27274900000003Ok
2 回答

翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
你不能取消一個 goroutine,除非你設計它被取消。您可以通過使用通道來表示正在計時的功能已完成,從而使計時功能短路:
func measureTime(expectedMs float64) (ok bool) {
done := make(chan struct{})
t1 := time.Now()
go func() {
funcWithUnpredictiveExecutionTime()
close(done)
}()
select {
case <-done:
ok = true
case <-time.After(time.Duration(expectedMs) * time.Millisecond):
}
fmt.Println(time.Since(t1))
return ok
}
- 2 回答
- 0 關注
- 207 瀏覽
添加回答
舉報
0/150
提交
取消