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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| package string2int
import ( "strconv" "testing" )
func loop(str string) int { num := 0 for i := 0; i < 8; i++ { num = num*10 + int(str[i]-'0') } return num }
func loop2(str string) int { num := 0 for i := 0; i < len(str); i++ { num = num*10 + int(str[i]-'0') } return num }
func unrollLoop(str string) int { num := int(str[0]-'0')*10000000 + int(str[1]-'0')*1000000 + int(str[2]-'0')*100000 + int(str[3]-'0')*10000 + int(str[4]-'0')*1000 + int(str[5]-'0')*100 + int(str[6]-'0')*10 + int(str[7]-'0') return num }
func simd() int { str := 0x3837363534333231 num := str & 0x0f0f0f0f0f0f0f0f num = (num&0x000f000f000f000f)*10 + (num>>8)&0x000f000f000f000f num = (num&0x0000007f0000007f)*100 + (num>>16)&0x0000007f0000007f num = (num&0x3fff)*10000 + (num>>32)&0x3fff return num }
func simd2() int { str := 0x3837363534333231 num := (str & 0x0f0f0f0f0f0f0f0f) * 2561 >> 8 num = (num & 0x00ff00ff00ff00ff) * 6553601 >> 16 num = (num & 0x0000ffff0000ffff) * 42949672960001 >> 32 return num }
func Test_String2Int(t *testing.T) { str := "12345678" n, _ := strconv.Atoi(str)
if loop(str) != n { t.Errorf("loop error, %v != %v\n", loop(str), n) } if loop2(str) != n { t.Errorf("loop2 error, %v != %v\n", loop2(str), n) } if unrollLoop(str) != n { t.Errorf("unroll loop error, %v != %v\n", unrollLoop(str), n) } if simd() != n { t.Errorf("simd error, %v != %v\n", simd(), n) } if simd2() != n { t.Errorf("simd2 error, %v != %v\n", simd2(), n) } }
func Benchmark_String2Int(b *testing.B) { str := "12345678" b.Run("strconv.Aoti", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { strconv.Atoi(str) } } }) b.Run("loop", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { loop(str) } } }) b.Run("loop2", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { loop2(str) } } }) b.Run("unroll loop", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { unrollLoop(str) } } }) b.Run("simd", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { simd() } } }) b.Run("simd2", func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < 1000; j++ { simd2() } } }) }
|