/** * Testign the speed of executable in Go. This just creates a large array and sorts it. * @author gtowell * created: July 20, 2021 **/ package main import ( "bytes" "fmt" "math/rand" "sort" "time" ) //Structs are a lot like classes, but with no inheritance. //Methods get added separately type NumAndString struct { num int str string } // name a type that will hold a list of items of the NumAndString type type NumAndStringSlice []NumAndString // by having another name, you can associate different sorting // sort of like static method binding type StringSlice NumAndStringSlice // create a variable that will hold a NumAndStringSlice var aaa NumAndStringSlice // implementing the function required for sorting func (p NumAndStringSlice) Len() int { return len(p) } func (p NumAndStringSlice) Swap(i, j int) { p[i],p[j] = p[j],p[i] } func (p NumAndStringSlice) Less(i, j int) bool { return p[i].num < p[j].num } // implementing the function required for sorting a different way. func (p StringSlice) Len() int { return len(p) } func (p StringSlice) Swap(i, j int) { p[i],p[j] = p[j],p[i] } func (p StringSlice) Less(i, j int) bool { return p[i].str < p[j].str } /** * Generate a random string * @param len -- the length of the string to generate * @param r1 an initialized random number generator instance * @return a random string */ func randString(len int, r1 *rand.Rand) string { var buf bytes.Buffer for i := 0; i < len; i++ { buf.WriteString(string('a' + r1.Intn(26))) } return buf.String() } func main() { s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) now := time.Now(); doSort(10000000, r1, false) thn := time.Now(); diff := thn.Sub(now) fmt.Println(diff); } /** * Create and fill an array of the desired size, then sort it. * report the time required for the two operations @param num the length of the array to create @param r1 a random number generator @param sortByNum how to sort the created array. **/ func doSort(num int, r1 *rand.Rand, sortByNum bool) { aaa = make(NumAndStringSlice, num) for i := 0; i < num; i++ { aaa[i] = NumAndString{r1.Intn(num), randString(10,r1)} } if (sortByNum) { sort.Sort(aaa) } else { sort.Sort(StringSlice(aaa)) } for i:=0; i < 5; i++ { fmt.Printf("%v\n", aaa[i]) } }