代码之家  ›  专栏  ›  技术社区  ›  Özgür Yalçın

有没有一种有效的方法来计算golang的执行时间?

  •  50
  • Özgür Yalçın  · 技术社区  · 7 年前

    func main() {
        start := time.Now()
    
        time.Sleep(time.Second * 2)
    
        //something doing here
    
        elapsed := time.Since(start)
        fmt.Printf("page took %s", elapsed)
    }
    

    上面的代码工作正常。

    有没有 有效率的 计算执行时间的方法,包括模板?

    4 回复  |  直到 3 年前
        1
  •  108
  •   Cerise Limón    2 年前

    如果要对整个函数计时,则可以使用 defer 消除一些重复代码。

    // timer returns a function that prints the name argument and 
    // the elapsed time between the call to timer and the call to
    // the returned function. The returned function is intended to
    // be used in a defer statement:
    //
    //   defer timer("sum")()
    func timer(name string) func() {
        start := time.Now()
        return func() {
            fmt.Printf("%s took %v\n", name, time.Since(start))
        }
    }
    
    func main() {
        defer timer("main")()  // <-- The trailing () is the deferred call
        time.Sleep(time.Second * 2)
    }   // prints: main took 2s
    

    Run the example on the playground .

    specification says this about deferred calls :

    每次执行“defer”语句时,调用的函数值和参数都会像往常一样进行评估并重新保存,但不会调用实际函数。相反,延迟函数在周围函数返回之前立即调用,

    函数值 timer("main") 在延迟声明中进行评估。这个 timer


    使用 runtime.Callers runtime.CallersFrames 自动获取调用函数的名称。

    // callerName returns the name of the function skip frames up the call stack.
    func callerName(skip int) string {
        const unknown = "unknown"
        pcs := make([]uintptr, 1)
        n := runtime.Callers(skip+2, pcs)
        if n < 1 {
            return unknown
        }
        frame, _ := runtime.CallersFrames(pcs).Next()
        if frame.Function == "" {
            return unknown
        }
        return frame.Function
    }
    
    // timer returns a function that prints the name of the calling
    // function and the elapsed time between the call to timer and
    // the call to the returned function. The returned function is
    // intended to be used in a defer statement:
    //
    //   defer timer()()
    func timer() func() {
        name := callerName(1)
        start := time.Now()
        return func() {
            fmt.Printf("%s took %v\n", name, time.Since(start))
        }
    }
    
    func main() {
        defer timer()()
        time.Sleep(time.Second * 2)
    }   // prints: main.main took 2s
    

    计时器 在录制开始时间之前获取名称。

    Run the example on the playground .

        2
  •  22
  •   Shiva    2 年前

    Bayta Darell 是完美的。


    此外,如果不想显式传递函数名,可以这样完成:

    func SomeFunction(list *[]string) {
        defer TimeTrack(time.Now())
        // Do whatever you want.
    }
    
    func TimeTrack(start time.Time) {
        elapsed := time.Since(start)
    
        // Skip this function, and fetch the PC and file for its parent.
        pc, _, _, _ := runtime.Caller(1)
    
        // Retrieve a function object this functions parent.
        funcObj := runtime.FuncForPC(pc)
    
        // Regex to extract just the function name (and not the module path).
        runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
        name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")
    
        log.Println(fmt.Sprintf("%s took %s", name, elapsed))
    }
    

    SomeFunction took 15.483µs


    有关更多信息,请参阅本文: Go Function Tracing

    分享知识。:)

        3
  •  4
  •   Uday Hiwarale    6 年前

    package main
    
    import (
        "fmt"
        "time"
    )
    
    var start time.Time
    
    func init() {
        start = time.Now()
    }
    
    func getChars(s string) {
        for _, c := range s {
            fmt.Printf("%c at time %v\n", c, time.Since(start))
            time.Sleep(10 * time.Millisecond)
        }
    }
    
    func main() {
        fmt.Println("main execution started at time", time.Since(start))
    
        getChars("Hello")
    
        fmt.Println("\nmain execution stopped at time", time.Since(start))
    }
    
        4
  •  2
  •   Community user43968    4 年前

    您可以轻松获得 执行时间 在控制台上使用延迟功能

    func main() {
        now := time.Now()
        defer func() {
            fmt.Println(time.Now().Sub(now))
        }()
            
        // Here you can do whatever you want
    }
    

    或者你可以使用这个代码

    func main() {
            now := time.Now()
            defer func() {
                fmt.Println(time.Since(now))
            }()
                
            // Here you can do whatever you want
        }
    

    签入代码 Playground