1

I am on the first chapter The Go Programming Language (Addison-Wesley Professional Computing Series) and the 3rd exercise in the book asks me to measure code performance using time.

So, I came up with the following code.

start := time.Now()
var s, sep string
for i := 1; i < len(os.Args); i++ {
    s += sep + os.Args[i]
    sep = " "
}
fmt.Print(s)
fmt.Printf("\nTook %.2fs \n", time.Since(start).Seconds())
fmt.Println("------------------------------------------------")
start2 := time.Now()
fmt.Print(strings.Join(os.Args[1:], " "))
fmt.Printf("\nTook %.2fs", time.Since(start2).Seconds())

When I ran this code on Windows and Mac, it always return 0.00 second. I added a pause in my code to check whether it's correct and it seems fine. What I don't understand is why it always returns 0.0.

icza
  • 389,944
  • 63
  • 907
  • 827
Cee
  • 29
  • 3

1 Answers1

11

There is very little code between your start times and the time.Since() calls, in the first example just a few string concatenations and an fmt.Print() call, in the second example just a single fmt.Print() call. These are executed by your computer very fast.

So fast, that the result is most likely less than a millisecond. And you print the elapsed time using the %.2f verb, which rounds the seconds to 2 fraction digits. Which means if the elapsed time is less than 0.005 sec, it will be rounded to 0. This is why you see 0.00s printed.

If you change the format to %0.12f, you will see something like:

Took 0.000027348000s 
Took 0.000003772000s

Also note that the time.Duration value returned by time.Since() implements fmt.Stringer, and it "formats" itself intelligently to a unit that is more meaningful. So you may print it as-is.

For example if you print it like this:

fmt.Println("Took", time.Since(start))
fmt.Println("Took", time.Since(start2))

You will see an output something like this:

Took 18.608µs
Took 2.873µs

Also note that if you want to measure the performance of some code, you should use Go's built-in testing and benchmarking facilities, namely the testing package. For details, see Order of the code and performance.

icza
  • 389,944
  • 63
  • 907
  • 827