title: measure execution time and stop waiting if too long in golang
body: <p>I am trying to measure execution time of <code>funcWithUnpredictiveExecutionTime</code> function. </p>
  
  <pre><code>func measureTime(expectedMs float64) (ok bool) {
      t1 := time.Now()
      funcWithUnpredictiveExecutionTime()
      t2 := time.Now()
      diff := t2.Sub(t1)
  </code></pre>
  
  <p>The measuring is fine when  <code>funcWithUnpredictiveExecutionTime</code> works faster than I expected. But if it works slower than <code>expectedMs</code>  the measuring will not stop right after expected amount of milliseconds passed. </p>
  
  <p>Is it possible to stop time measuring when <code>funcWithUnpredictiveExecutionTime</code> works longer than <code>expectedMs</code> without waiting <code>funcWithUnpredictiveExecutionTime</code> to finish?</p>
  
  <p>In other words, <code>measureTime(200)</code> should return in <code>200 ms</code> anyway with a good or bad result.</p>
  
  <p>I guess I should use channels and then somehow cancel waiting for a channel. But how to do it exactly?</p>
  
  <p>Full code:</p>
  
  <pre><code>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 &lt; 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 &lt; 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
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Sleeping for 422 milliseconds
  424.11895200000004
  Too late
  Sleeping for 422 milliseconds
  425.27274900000003
  Ok
  </code></pre>
  
  <p><a href="http://play.golang.org/p/YP6GxoiSbg" rel="nofollow">Playground</a></p>