Skip to content

Instantly share code, notes, and snippets.

@larytet
Last active September 20, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larytet/b864982d32ac31fedbbed2ffdac9dc85 to your computer and use it in GitHub Desktop.
Save larytet/b864982d32ac31fedbbed2ffdac9dc85 to your computer and use it in GitHub Desktop.
func prepareNonuniform(size int) []int {
samples := make([]int, size, size)
for i := 0; i < size; i++ {
for {
grg := gaussian()
index := int(((2.0 + grg) / 4.0) * float64(size-1))
if (index >= 0) && (index < size) {
samples[i] = index
break
}
}
}
return samples
}
// Run the same test with the Go map API for comparison
func BenchmarkMapStore(b *testing.B) {
b.ReportAllocs()
//b.N = 100 * 1000
keys := make([]string, b.N, b.N)
for i := 0; i < b.N; i++ {
keys[i] = fmt.Sprintf("%d", b.N-i)
}
m := make(map[string]uintptr, b.N)
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := keys[i]
m[key] = uintptr(i)
}
}
func BenchmarkMapStoreNonuniform(b *testing.B) {
b.ReportAllocs()
//b.N = 100 * 1000
keys := make([]string, b.N, b.N)
for i := 0; i < b.N; i++ {
keys[i] = fmt.Sprintf("%d", b.N-i)
}
samples := prepareNonuniform(b.N)
m := make(map[string]uintptr, b.N)
b.ResetTimer()
skipped := 0
for i := 0; i < b.N; i++ {
sample := samples[i]
if sample < 0 || sample >= b.N {
//b.Logf("Skipped %d", sample)
skipped++
continue
}
key := keys[sample]
m[key] = uintptr(i)
}
b.Logf("Skipped total %d", skipped)
}
func BenchmarkMapLoadNonuniform(b *testing.B) {
b.ReportAllocs()
//b.N = 100 * 1000
keys := make([]string, b.N, b.N)
for i := 0; i < b.N; i++ {
keys[i] = fmt.Sprintf("%d", b.N-i)
}
samples := prepareNonuniform(b.N)
m := make(map[string]uintptr, b.N)
for i := 0; i < b.N; i++ {
sample := samples[i]
if sample < 0 || sample >= b.N {
continue
}
key := keys[sample]
m[key] = uintptr(i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
sample := samples[i]
if sample < 0 || sample >= b.N {
continue
}
key := keys[sample]
v := m[key]
if v != uintptr(i) {
b.Fatalf("Wrong value %d, expected %d", v, i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment