1
0
mirror of synced 2026-04-18 22:38:41 +08:00

!1 optimize golang code

* use lock and bit operation
This commit is contained in:
微希夷
2021-03-25 12:58:27 +08:00
committed by yitter
parent 3a2013982f
commit f4955a7ba4
2 changed files with 6 additions and 6 deletions

View File

@@ -7,7 +7,6 @@
package core
import (
"math"
"sync"
"time"
"yitidgen/contract"
@@ -53,7 +52,7 @@ func NewSnowWorkerM1(options *contract.IdGeneratorOptions) contract.ISnowWorker
if options.MaxSeqNumber > 0 {
maxSeqNumber = options.MaxSeqNumber
} else {
maxSeqNumber = uint32(math.Pow(2, float64(options.SeqBitLength))) - 1
maxSeqNumber = (1 << seqBitLength) - 1
}
var minSeqNumber = options.MinSeqNumber
var topOverCostCount = options.TopOverCostCount

View File

@@ -9,7 +9,6 @@ package core
import (
"fmt"
"strconv"
"sync/atomic"
"yitidgen/contract"
)
@@ -24,15 +23,17 @@ func NewSnowWorkerM2(options *contract.IdGeneratorOptions) contract.ISnowWorker
}
func (m2 SnowWorkerM2) NextId() uint64 {
m2.Lock()
defer m2.Unlock()
currentTimeTick := m2.GetCurrentTimeTick()
if m2._LastTimeTick == currentTimeTick {
atomic.AddUint32(&m2._CurrentSeqNumber, 1)
m2._CurrentSeqNumber++
if m2._CurrentSeqNumber > m2.MaxSeqNumber {
atomic.StoreUint32(&m2._CurrentSeqNumber, uint32(m2.MinSeqNumber))
m2._CurrentSeqNumber = m2.MinSeqNumber
currentTimeTick = m2.GetNextTimeTick()
}
} else {
atomic.StoreUint32(&m2._CurrentSeqNumber, uint32(m2.MinSeqNumber))
m2._CurrentSeqNumber = m2.MinSeqNumber
}
if currentTimeTick < m2._LastTimeTick {
fmt.Println("Time error for {0} milliseconds", strconv.FormatInt(m2._LastTimeTick-currentTimeTick, 10))