Browse Source

!1 optimize golang code

* use lock and bit operation
tags/v1.0.0
微希夷 yitter 3 years ago
parent
commit
f4955a7ba4
2 changed files with 6 additions and 6 deletions
  1. +1
    -2
      Go/source/core/snowWorkerM1.go
  2. +5
    -4
      Go/source/core/snowWorkerM2.go

+ 1
- 2
Go/source/core/snowWorkerM1.go View File

@@ -7,7 +7,6 @@
package core package core


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


+ 5
- 4
Go/source/core/snowWorkerM2.go View File

@@ -9,7 +9,6 @@ package core
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"sync/atomic"
"yitidgen/contract" "yitidgen/contract"
) )


@@ -24,15 +23,17 @@ func NewSnowWorkerM2(options *contract.IdGeneratorOptions) contract.ISnowWorker
} }


func (m2 SnowWorkerM2) NextId() uint64 { func (m2 SnowWorkerM2) NextId() uint64 {
m2.Lock()
defer m2.Unlock()
currentTimeTick := m2.GetCurrentTimeTick() currentTimeTick := m2.GetCurrentTimeTick()
if m2._LastTimeTick == currentTimeTick { if m2._LastTimeTick == currentTimeTick {
atomic.AddUint32(&m2._CurrentSeqNumber, 1)
m2._CurrentSeqNumber++
if m2._CurrentSeqNumber > m2.MaxSeqNumber { if m2._CurrentSeqNumber > m2.MaxSeqNumber {
atomic.StoreUint32(&m2._CurrentSeqNumber, uint32(m2.MinSeqNumber))
m2._CurrentSeqNumber = m2.MinSeqNumber
currentTimeTick = m2.GetNextTimeTick() currentTimeTick = m2.GetNextTimeTick()
} }
} else { } else {
atomic.StoreUint32(&m2._CurrentSeqNumber, uint32(m2.MinSeqNumber))
m2._CurrentSeqNumber = m2.MinSeqNumber
} }
if currentTimeTick < m2._LastTimeTick { if currentTimeTick < m2._LastTimeTick {
fmt.Println("Time error for {0} milliseconds", strconv.FormatInt(m2._LastTimeTick-currentTimeTick, 10)) fmt.Println("Time error for {0} milliseconds", strconv.FormatInt(m2._LastTimeTick-currentTimeTick, 10))


Loading…
Cancel
Save