How to measure function execution time in Go

1 Answer

0 votes
// Measuring function execution time in 
// Go using a reusable Timer (milliseconds + seconds)

package main

import (
    "fmt"
    "time"
)

// ---------------------------
// Reusable Timer struct
// ---------------------------
type Timer struct {
    start time.Time
    end   time.Time
}

// Start the timer
func (t *Timer) Start() {
    t.start = time.Now()
}

// Stop the timer
func (t *Timer) Stop() {
    t.end = time.Now()
}

// Return elapsed time in milliseconds
func (t *Timer) ElapsedMilliseconds() float64 {
    return float64(t.end.Sub(t.start).Milliseconds())
}

// Return elapsed time in seconds
func (t *Timer) ElapsedSeconds() float64 {
    return t.end.Sub(t.start).Seconds()
}

// ---------------------------
// Function to measure
// ---------------------------
func work() {
    sum := 0
    for i := 0; i < 100000000; i++ {
        sum += i
    }
}

// ---------------------------
// Main program
// ---------------------------
func main() {
    var t Timer

    t.Start()
    work()
    t.Stop()

    ms := t.ElapsedMilliseconds()
    sec := t.ElapsedSeconds()

    fmt.Println("Execution time:", ms, "ms")
    fmt.Println("Execution time:", sec, "seconds")
}



/* 
run:

Execution time: 33 ms
Execution time: 0.033742308 seconds

*/

 



answered 4 hours ago by avibootz
...