Skip to content

Instantly share code, notes, and snippets.

@aonemd
Last active February 14, 2016 23:01
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 aonemd/374bb16638a51c0d8728 to your computer and use it in GitHub Desktop.
Save aonemd/374bb16638a51c0d8728 to your computer and use it in GitHub Desktop.
Go Benchmark for Subset Function
#!/bin/sh
# to run the benchmark
go test -bench=.
package main
func subsetOfCount(child, parent []int) bool {
// http://stackoverflow.com/a/18879994/4352712
set := make(map[int]int)
for _, value := range parent {
set[value] += 1
}
for _, value := range child {
if count, found := set[value]; !found {
return false
} else if count < 1 {
return false
} else {
set[value] = count - 1
}
}
return true
}
// Does not care about duplicates
func subsetOfBool(child, parent []int) bool {
seen := make(map[int]bool)
for _, element := range parent {
seen[element] = true
}
for _, element := range child {
if !seen[element] {
return false
}
}
return true
}
package main
import "testing"
func BenchmarkSubsetOfCount(b *testing.B) {
for n := 0; n < b.N; n++ {
subsetOfCount([]int{1, 2, 3}, []int{1, 2, 3, 4})
}
}
func BenchmarkSubsetOfBool(b *testing.B) {
for n := 0; n < b.N; n++ {
subsetOfBool([]int{1, 2, 3}, []int{1, 2, 3, 4})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment