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

我正在尝试测量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 main


import (

    "fmt"

    "math/rand"

    "time"

)


// random number between min and max

func 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 1000

func 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 funcWithUnpredictiveExecutionTime

func 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 late

func 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 milliseconds

424.11895200000004

Too late

Sleeping for 422 milliseconds

425.27274900000003

Ok


沧海一幻觉
浏览 177回答 2
2回答

翻过高山走不出你

你不能取消一个 goroutine,除非你设计它被取消。您可以通过使用通道来表示正在计时的功能已完成,从而使计时功能短路:func measureTime(expectedMs float64) (ok bool) {&nbsp; &nbsp; done := make(chan struct{})&nbsp; &nbsp; t1 := time.Now()&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; funcWithUnpredictiveExecutionTime()&nbsp; &nbsp; &nbsp; &nbsp; close(done)&nbsp; &nbsp; }()&nbsp; &nbsp; select {&nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; ok = true&nbsp; &nbsp; case <-time.After(time.Duration(expectedMs) * time.Millisecond):&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(time.Since(t1))&nbsp; &nbsp; return ok}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go