Last active
February 14, 2016 23:01
-
-
Save aonemd/374bb16638a51c0d8728 to your computer and use it in GitHub Desktop.
Go Benchmark for Subset Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# to run the benchmark | |
go test -bench=. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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