57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package robot
|
||
|
||
import (
|
||
"encoding/hex"
|
||
"math/rand"
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
// 长度为62
|
||
var nbytes []byte = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890")
|
||
|
||
func init() {
|
||
// 保证每次生成的随机数不一样
|
||
rand.Seed(time.Now().UnixNano())
|
||
}
|
||
|
||
// 方法一
|
||
func (r *Robot) RandStr1(n int) string {
|
||
result := make([]byte, n)
|
||
for i := 0; i < n; i++ {
|
||
result[i] = nbytes[rand.Int31()%62]
|
||
}
|
||
return string(result)
|
||
}
|
||
|
||
// 方法二
|
||
func (r *Robot) RandStr2(n int) string {
|
||
result := make([]byte, n/2)
|
||
rand.Read(result)
|
||
return hex.EncodeToString(result)
|
||
}
|
||
|
||
// 对比一下两种方法的性能
|
||
func (r *Robot) Benchmark1(b *testing.B) {
|
||
b.RunParallel(func(pb *testing.PB) {
|
||
for pb.Next() {
|
||
r.RandStr1(12)
|
||
}
|
||
})
|
||
// 结果:539.1 ns/op
|
||
}
|
||
|
||
func (r *Robot) Benchmark2(b *testing.B) {
|
||
b.RunParallel(func(pb *testing.PB) {
|
||
for pb.Next() {
|
||
r.RandStr2(12)
|
||
}
|
||
})
|
||
// 结果: 157.2 ns/op
|
||
}
|
||
|
||
// func TestOne(t *testing.T) {
|
||
// fmt.Println("方法一生成12位随机字符串: ", RandStr1(12))
|
||
// fmt.Println("方法二生成12位随机字符串: ", RandStr2(12))
|
||
// }
|