Skip to content

Instantly share code, notes, and snippets.

@Nirma
Created December 28, 2015 12:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Nirma/c3faac6c5c8d8f30468f to your computer and use it in GitHub Desktop.
Save Nirma/c3faac6c5c8d8f30468f to your computer and use it in GitHub Desktop.
Using Decorators in Golang to profile performance
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
stable := timedSortFunc(sort.Stable)
unStable := timedSortFunc(sort.Sort)
randomCatList1 := randomCatScoreSlice(10000, 5000)
randomCatList2 := randomCatScoreSlice(10000, 5000)
fmt.Printf("Unstable Sorting Function:\n")
stable(randomCatList1)
fmt.Printf("Stable Sorting Function:\n")
unStable(randomCatList2)
}
type SortFunc func(sort.Interface)
func timedSortFunc(f SortFunc) SortFunc {
return func(data sort.Interface) {
defer func(t time.Time) {
fmt.Printf("--- Time Elapsed: %v ---\n", time.Since(t))
}(time.Now())
f(data)
}
}
func randomCatScoreSlice(size int, upperLimit int) CatScoreList {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
catScores := make(CatScoreList, size)
for i, _ := range catScores {
cat := catScores[i]
cat.name = "Fluffy"
cat.likeCount = r.Intn(upperLimit)
}
return catScores
}
//Definition of CatScore struct
type CatScore struct {
likeCount int
name string
}
type CatScoreList []CatScore
func (s CatScoreList) Len() int {
return len(s)
}
func (s CatScoreList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s CatScoreList) Less(i, j int) bool {
return s[i].likeCount < s[j].likeCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment