Well, I forgot to mention that secs will contain an integer number of seconds (assumed "%ds" fmt.Printf format). The example should have used an explicit conversion to an int, though.
(phone)
-j
Am I missing an obvious way of doing this or should there be a Round method on Duration?
To log a time difference I initially coded:start := time.Now()...fmt.Printf("...took %s\n", time.Since(start))but that resulted in an output of 19.7996387s which is impressive in its resolution but I really only wanted a display resolution to the second.So I thought the natural thing would be to call:time.Since(start).Round(time.Second)but there is no Round method on Duration, only on a Time. So I resorted to:start := time.Now().Round(time.Second)...end := := time.Now().Round(time.Second)fmt.Printf("...took %s\n", end.Sub(start))
--
Bravo Andrew!!!This is indeed what I had been wanting: the automatic formatting range of the existing Duration with the arbitrary precision of the Time.Round function. With all due respect to Rob with his "Just write the code", it didn't seem that obvious and I would certainly never have come up with anything this elegant.
My first instinct was along the lines of Jan's:( (dur + resolution/2)/resolution) * resolution but there's no hint of a 2 in your code so it will take me a while to grok it. But it does far better than my simple rounding of both timing endpoints so it doesn't affect their precision.
As is often the case, after posing my "simple" question and then being asked "Is this what you want" it occurred to me that what might also be useful was to print a duration with a "sensible" precision like 2 or 3 digits. Is there a way to use your function (other than a switch or if/else chain based on the value of d) that would achieve this? I tried a very naive making r a function of d as here where n was intended to be the approx digits of precision but it failed horribly:switch n {case 1:r = d / 10case 2:r = d / 100case 3:r = d / 1000case 4:r = d / 10000case 5:r = d / 100000case 6:r = d / 10000000}
Thanks to you and all the others for your suggestions,Gary
Here's a rounding function: http://play.golang.org/p/QHocTHl8iR