github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/math/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 if isRaceBuilder && (aSize > 1000 || bSize > 1000) { 24 b.Skip("skipping on race builder") 25 } 26 b.Run("WithoutXY", func(b *testing.B) { 27 runGCDExt(b, aSize, bSize, false) 28 }) 29 b.Run("WithXY", func(b *testing.B) { 30 runGCDExt(b, aSize, bSize, true) 31 }) 32 } 33 34 func runGCDExt(b *testing.B, aSize, bSize uint, calcXY bool) { 35 b.StopTimer() 36 var r = rand.New(rand.NewSource(1234)) 37 aa := randInt(r, aSize) 38 bb := randInt(r, bSize) 39 var x, y *Int 40 if calcXY { 41 x = new(Int) 42 y = new(Int) 43 } 44 b.StartTimer() 45 for i := 0; i < b.N; i++ { 46 new(Int).GCD(x, y, aa, bb) 47 } 48 } 49 50 func BenchmarkGCD10x10(b *testing.B) { runGCD(b, 10, 10) } 51 func BenchmarkGCD10x100(b *testing.B) { runGCD(b, 10, 100) } 52 func BenchmarkGCD10x1000(b *testing.B) { runGCD(b, 10, 1000) } 53 func BenchmarkGCD10x10000(b *testing.B) { runGCD(b, 10, 10000) } 54 func BenchmarkGCD10x100000(b *testing.B) { runGCD(b, 10, 100000) } 55 func BenchmarkGCD100x100(b *testing.B) { runGCD(b, 100, 100) } 56 func BenchmarkGCD100x1000(b *testing.B) { runGCD(b, 100, 1000) } 57 func BenchmarkGCD100x10000(b *testing.B) { runGCD(b, 100, 10000) } 58 func BenchmarkGCD100x100000(b *testing.B) { runGCD(b, 100, 100000) } 59 func BenchmarkGCD1000x1000(b *testing.B) { runGCD(b, 1000, 1000) } 60 func BenchmarkGCD1000x10000(b *testing.B) { runGCD(b, 1000, 10000) } 61 func BenchmarkGCD1000x100000(b *testing.B) { runGCD(b, 1000, 100000) } 62 func BenchmarkGCD10000x10000(b *testing.B) { runGCD(b, 10000, 10000) } 63 func BenchmarkGCD10000x100000(b *testing.B) { runGCD(b, 10000, 100000) } 64 func BenchmarkGCD100000x100000(b *testing.B) { runGCD(b, 100000, 100000) }