第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

測量執(zhí)行時間并停止等待如果在 golang 中太長

測量執(zhí)行時間并停止等待如果在 golang 中太長

Go
滄海一幻覺 2021-10-18 10:12:46
我正在嘗試測量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


}


查看完整回答
反對 回復 2021-10-18
  • 2 回答
  • 0 關注
  • 207 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號