Skip to content

Commit

Permalink
Merge pull request #19 from nishaad78/monotonic_clock
Browse files Browse the repository at this point in the history
Optimize monotonic clock code
  • Loading branch information
bwmarrin authored Apr 11, 2019
2 parents 652d4f1 + 4c4a279 commit 7dcf86e
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions snowflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ var ErrInvalidBase32 = errors.New("invalid base32")
type Node struct {
mu sync.Mutex
epoch time.Time
time time.Duration
time int64
node int64
step int64

Expand Down Expand Up @@ -132,14 +132,14 @@ func (n *Node) Generate() ID {

n.mu.Lock()

now := time.Since(n.epoch)
now := time.Since(n.epoch).Nanoseconds() / 1000000

if now-n.time < time.Millisecond {
if now == n.time {
n.step = (n.step + 1) & n.stepMask

if n.step == 0 {
for now-n.time < time.Millisecond {
now = time.Since(n.epoch)
for now <= n.time {
now = time.Since(n.epoch).Nanoseconds() / 1000000
}
}
} else {
Expand All @@ -148,7 +148,7 @@ func (n *Node) Generate() ID {

n.time = now

r := ID((now.Nanoseconds()/1000000)<<n.timeShift |
r := ID((now)<<n.timeShift |
(n.node << n.nodeShift) |
(n.step),
)
Expand Down

0 comments on commit 7dcf86e

Please sign in to comment.