1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| func doPercent(n int, divisor int) int{ return n % divisor }
func doAnd(n int, divisor int) int { return n & (divisor -1) }
func TestMod(t *testing.T) { testCase := []struct{ N int Div int Expect int }{ { N: 4, Div: 2, Expect: 0, }, { N: 15, Div: 8, Expect: 7, }, { N: 5, Div: 8, Expect: 5, }, { N: 5, Div: 1, Expect: 0, }, { N: 0, Div: 2, Expect: 0, }, { N: 1<<31, Div: 1<<30, Expect: 0, },
} for _, c := range testCase { t.Run(fmt.Sprintf("n: %v, div: %v, expect: %v", c.N, c.Div,c.Expect), func(t *testing.T) { assert.Equal(t, c.Expect, doPercent(c.N,c.Div)) assert.Equal(t, c.Expect, doAnd(c.N,c.Div)) }) } }
func BenchmarkMod(b *testing.B) { testCase := []struct{ N int Div int Expect int }{ { N: 4, Div: 2, Expect: 0, }, { N: 15, Div: 8, Expect: 7, }, { N: 1<<13+ 1<< 10 + 12345, Div: 8, Expect: 7, }, { N: 1<<30 + 13, Div: 1<<16, Expect: 0, },
} for _, c := range testCase { b.Run(fmt.Sprintf("test do percent with n: %v, div: %v",c.N,c.Div),func (b *testing.B) { for i := 0; i < b.N; i++ { doPercent(c.N,c.Div) } }) b.Run(fmt.Sprintf("test do and with n: %v, div: %v",c.N,c.Div),func (b *testing.B) { for i := 0; i < b.N; i++ { doAnd(c.N,c.Div) } }) } }
|