为了账号安全,请及时绑定邮箱和手机立即绑定

测量执行时间并停止等待如果在 golang 中太长

测量执行时间并停止等待如果在 golang 中太长

Go
沧海一幻觉 2021-10-18 10:12:46
我正在尝试测量funcWithUnpredictiveExecutionTime函数的执行时间。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 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信