* Warren Bare <warren.b...@gmail.com> [200519 13:53]:
> OK, I added a sum of the rand to the demo code and the results are the 
> same.  Since it is displaying the sum, it seems clear that the code is not 
> optimized away.
> 
> Again, I am NOT trying to time each iteration of the loop.  This is a 
> minimal demonstration of a weirdness I was seeing in my own benchmarks.  
> Just pretend the loop is one chunk of code that takes time and is not 
> optimized away.
> 
> Any other ideas?
> 
> func BenchmarkMarshalSample(b *testing.B) {
>     var sum int64
>     start := time.Now()
>     for i := 0; i < 10_000_000; i++ {
>         sum += rand.Int63n(0xFFFFFFFF)
>     }
>     b.Logf("Sum %e Duration %v", float64(sum), time.Now().Sub(start))
> }

You do not clearly understand how benchmarking in the testing package
works.  In order to get meaningful results, your benchmark function
_must_ iterate b.N times.  The benchmark framework is going to run your
function several times, with different values of b.N until it can get a
meaningful time, and then it does the math to give you "per iteration"
times.  Read carefully the section "Benchmarks" under
https://golang.org/pkg/testing/.

For the above case (given that you are not trying to time one
invocation of rand.Int63n, but a fixed number) you would write your code
like this:

func BenchmarkMarshalSample(b *testing.B) {
    var sum int64
    start := time.Now()
    for j := 0; j < b.N; j++ {
        for i := 0; i < 10_000_000; i++ {
            sum += rand.Int63n(0xFFFFFFFF)
        }
    }
    b.Logf("Sum %e Duration %v", float64(sum), time.Now().Sub(start))
}

The benchmark results will give the time for _one_ iteration of the
_outer_ loop, so the "op" in "ns/op" will be 10_000_000 iterations of
the inner loop.

...Marvin

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/20200519181906.5xvifyyrowbnfzrs%40basil.wdw.

Reply via email to