Skip to content

Instantly share code, notes, and snippets.

@mertakman
Created May 12, 2021 14:11
Show Gist options
  • Save mertakman/7887420258464fbe0074428fefacb090 to your computer and use it in GitHub Desktop.
Save mertakman/7887420258464fbe0074428fefacb090 to your computer and use it in GitHub Desktop.
UnixNano Collision
/*
UnixNano method has time-sensitivity between 40-500 nanoseconds.
Likely to produce the same output for few simultaneous goroutines within
the same period. Do not rely on UnixNano result being unique.
*/
package main
import (
"fmt"
"sync"
"time"
)
const tryingCount = 150
func main() {
var timeStampsSlice []int64 // storage of unix timestamps
var wg sync.WaitGroup
var mt sync.Mutex
for z := 0; z < 100; z++ {
for i := 0; i < tryingCount; i++ {
wg.Add(1)
go func() {
tf := time.Now().UnixNano()
mt.Lock()
timeStampsSlice = append(timeStampsSlice, tf)
mt.Unlock()
wg.Done()
}()
}
wg.Wait()
if mapReturn := duplicateCount(timeStampsSlice); len(mapReturn) != 0 {
for timeStamp, repeatCount := range mapReturn {
fmt.Printf("Timestamp : %d repeated %d times. \n", timeStamp, repeatCount)
}
}
timeStampsSlice = timeStampsSlice[:0]
}
}
func duplicateCount(list []int64) map[int64]int {
duplicateFrequency := make(map[int64]int)
for _, item := range list {
_, exist := duplicateFrequency[item]
if exist {
duplicateFrequency[item]++
} else {
duplicateFrequency[item] = 1
}
}
for k, v := range duplicateFrequency {
if v == 1 {
delete(duplicateFrequency, k)
}
}
return duplicateFrequency
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment