Golang is a simple way to record and calculate the execution time and run time of a function

  • 2020-05-30 20:23:10
  • OfStack

Write a public function first. For example, there is a method under the common package:


//  Write a timeout warning log   Common methods 

func TimeoutWarning(tag, detailed string, start time.Time, timeLimit float64) {
  dis := time.Now().Sub(start).Seconds()
  if dis > timeLimit {
    log.Warning(log.CENTER_COMMON_WARNING, tag, " detailed:", detailed, "TimeoutWarning using", dis, "s")
    //pubstr := fmt.Sprintf("%s count %v, using %f seconds", tag, count, dis)
    //stats.Publish(tag, pubstr)
  }
}


Several parameters of this function are explained as follows:
tag and detailed represent two string arguments to where the timeout occurred.
The time when the start program begins execution
The timeLimit function executes the timeout threshold in seconds.
When used, the following code is placed on line 1 of each function:


//

func Save The function name ( ... ) ( ... ) {
  //  If this method executes a timeout 3 Seconds, the log will be logged 
  defer common.TimeoutWarning("SaveAppLogMain", "Total", time.Now(), float64(3))
  //  ...   The logic of the function itself. 
}


Related articles: