Skip to content

Instantly share code, notes, and snippets.

@WorldDownTown
Forked from Nirma/Decorators.go
Created March 24, 2016 02:18
Show Gist options
  • Save WorldDownTown/e1aafac4bc3d49637669 to your computer and use it in GitHub Desktop.
Save WorldDownTown/e1aafac4bc3d49637669 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