github.com/euank/go@v0.0.0-20160829210321-495514729181/src/cmd/compile/internal/big/gcd_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements a GCD benchmark.
     6  // Usage: go test math/big -test.bench GCD
     7  
     8  package big
     9  
    10  import (
    11  	"math/rand"
    12  	"testing"
    13  )
    14  
    15  // randInt returns a pseudo-random Int in the range [1<<(size-1), (1<<size) - 1]
    16  func randInt(r *rand.Rand, size uint) *Int {
    17  	n := new(Int).Lsh(intOne, size-1)
    18  	x := new(Int).Rand(r, n)
    19  	return x.Add(x, n) // make sure result > 1<<(size-1)
    20  }
    21  
    22  func runGCD(b *testing.B, aSize, bSize uint) {
    23  	b.Run("WithoutXY", func(b *testing.B) {
    24  		runGCDExt(b, aSize, bSize, false)
    25  	})
    26  	b.Run("WithXY", func(b *testing.B) {
    27  		runGCDExt(b, aSize, bSize, true)
    28  	})
    29  }
    30  
    31  func runGCDExt(b *testing.B, aSize, bSize uint, calcXY bool) {
    32  	b.StopTimer()
    33  	var r = rand.New(rand.NewSource(1234))
    34  	aa := randInt(r, aSize)
    35  	bb := randInt(r, bSize)
    36  	var x, y *Int
    37  	if calcXY {
    38  		x = new(Int)
    39  		y = new(Int)
    40  	}
    41  	b.StartTimer()
    42  	for i := 0; i < b.N; i++ {
    43  		new(Int).GCD(x, y, aa, bb)
    44  	}
    45  }
    46  
    47  func BenchmarkGCD10x10(b *testing.B)         { runGCD(b, 10, 10) }
    48  func BenchmarkGCD10x100(b *testing.B)        { runGCD(b, 10, 100) }
    49  func BenchmarkGCD10x1000(b *testing.B)       { runGCD(b, 10, 1000) }
    50  func BenchmarkGCD10x10000(b *testing.B)      { runGCD(b, 10, 10000) }
    51  func BenchmarkGCD10x100000(b *testing.B)     { runGCD(b, 10, 100000) }
    52  func BenchmarkGCD100x100(b *testing.B)       { runGCD(b, 100, 100) }
    53  func BenchmarkGCD100x1000(b *testing.B)      { runGCD(b, 100, 1000) }
    54  func BenchmarkGCD100x10000(b *testing.B)     { runGCD(b, 100, 10000) }
    55  func BenchmarkGCD100x100000(b *testing.B)    { runGCD(b, 100, 100000) }
    56  func BenchmarkGCD1000x1000(b *testing.B)     { runGCD(b, 1000, 1000) }
    57  func BenchmarkGCD1000x10000(b *testing.B)    { runGCD(b, 1000, 10000) }
    58  func BenchmarkGCD1000x100000(b *testing.B)   { runGCD(b, 1000, 100000) }
    59  func BenchmarkGCD10000x10000(b *testing.B)   { runGCD(b, 10000, 10000) }
    60  func BenchmarkGCD10000x100000(b *testing.B)  { runGCD(b, 10000, 100000) }
    61  func BenchmarkGCD100000x100000(b *testing.B) { runGCD(b, 100000, 100000) }