Measure execution time of a fast operation

Hello,
I want to measure the execution time of a subroutine that takes very little time. A simple example:

package main

import (
	"fmt"
	"time"
)

func main() {
	timer:= time.Now()
	fmt.Println("Hello, playground")
	fmt.Printf("(Execution time: %s) |", time.Since(timer))
}

This always returns 0s, however I need to measure this somehow (i.e. need higher resolution). Any suggestions? Thanks!

Not for me:

$ go run main.go
Hello, playground
(Execution time: 29.073µs) |
$ go run main.go
Hello, playground
(Execution time: 21.639µs) |
$ go run main.go
Hello, playground
(Execution time: 21.575µs) |
$ go run main.go
Hello, playground
(Execution time: 20.104µs) |
$ go run main.go
Hello, playground
(Execution time: 22.327µs) |

Perhaps you tested on a system that hasn’t a precise enough clock? Or perhaps you tested on the playground, where the clock doesn’t advance?

If this is for benchmarking, use a benchmark: https://golang.org/pkg/testing/#hdr-Benchmarks

If it’s not for benchmarking, and you’re on a system with low resolution timers (Windows), I guess it’s short enough to not worry about. :slight_smile:

Yes my system runs Windows. I will run it on Ubuntu and see what I get. Will look into benchmarking as well…

I confirm that running the code on Ubuntu returns some value of microseconds instead of just zero. Would be nice to know if there’s a fix for Windows…

No, there is no fix for that. Even high resolution timers will not be finer than 0.5ms per tick as far as I understand the results I get from Google.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.