改进grand随机数生成设计,底层使用crypto/rand+缓冲区实现高速的随机数生成;gtime模块增加FuncCost函数执行耗时计算

This commit is contained in:
john
2018-11-05 13:53:17 +08:00
parent 1f5834d94c
commit d257e554dd
9 changed files with 154 additions and 18 deletions

View File

@ -26,7 +26,7 @@ type Session struct {
server *Server // 所属Server
}
// 生成一个唯一的sessionid字符串
// 生成一个唯一的sessionid字符串长度16
func makeSessionId() string {
return strings.ToUpper(strconv.FormatInt(gtime.Nanosecond(), 32) + grand.RandStr(3))
}

View File

@ -306,4 +306,11 @@ func ParseTimeFromContent(content string, format...string) *Time {
}
}
return nil
}
// 计算函数f执行的时间单位纳秒
func FuncCost(f func()) int64 {
t := Nanosecond()
f()
return Nanosecond() - t
}

View File

@ -15,7 +15,7 @@ import (
"strings"
)
// 将变量i转换为字符串指定的类型t非必须参数extraParams泳衣额外的参数传递
// 将变量i转换为字符串指定的类型t非必须参数extraParams用以额外的参数传递
func Convert(i interface{}, t string, extraParams...interface{}) interface{} {
switch t {
case "int": return Int(i)

View File

@ -7,18 +7,9 @@
// 随机数管理
package grand
import (
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var digits = []rune("0123456789")
// 自定义的 rand.Intn
func intn (max int) int {
return int(time.Now().UnixNano())%max
}
// 获得一个 min, max 之间的随机数(min <= x <= max)
func Rand (min, max int) int {
if min >= max {

View File

@ -0,0 +1,45 @@
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gf.
package grand
import (
"crypto/rand"
"encoding/binary"
)
const (
gBUFFER_SIZE = 10000 // 缓冲区uint64数量大小
)
var (
bufferChan = make(chan uint64, gBUFFER_SIZE)
)
// 使用缓冲区实现快速的随机数生成
func init() {
buffer := make([]byte, 1024)
go func() {
for {
if n, err := rand.Read(buffer); err != nil {
panic(err)
} else {
for i := 0; i < n - 8; i += 8 {
bufferChan <- binary.LittleEndian.Uint64(buffer[i : i + 8])
}
}
}
}()
}
// 自定义的 rand.Intn ,绝对随机
func intn (max int) int {
n := int(<- bufferChan)%max
if n < 0 {
return -n
}
return n
}

View File

@ -15,6 +15,6 @@ import (
func Benchmark_Rand(b *testing.B) {
for i := 0; i < b.N; i++ {
grand.Rand(0, 200)
grand.Rand(0, 999999999)
}
}