Used closures instead of strings for the generic sorter. This removed the need for reflection.

This commit is contained in:
Pradyumna Kaushik 2017-08-26 15:19:30 -04:00
parent 3c65bdf02e
commit 0869bea2d8
2 changed files with 10 additions and 30 deletions

View file

@ -1,29 +1,13 @@
package def
// Creating an enumeration of the resources in def.Task.
var taskResourceNames []string
type sortCriteria int
// Map a task's resource name to the sorting criteria (an integer corresponding to the enumeration).
func resourceToSortCriteria(resourceName string) sortCriteria {
// Appending resourceName to TaskResourceNames.
taskResourceNames = append(taskResourceNames, resourceName)
// Considering index of resource in TaskResourceNames to be the int mapping.
return sortCriteria(len(taskResourceNames) - 1)
}
func (sc sortCriteria) String() string {
return taskResourceNames[int(sc)]
}
// the sortBy function that takes a task reference and returns the resource to consider when sorting.
type sortBy func (task *Task) float64
// Possible Sorting Criteria
// Note: the value of the string passed as argument to resourceToSortCriteria() should be the same (case-sensitive)
// as the name of the of the corresponding resource in the struct.
// Each holds a closure that fetches the required resource from the
// given task reference.
var (
CPU = resourceToSortCriteria("CPU")
RAM = resourceToSortCriteria("RAM")
Watts = resourceToSortCriteria("Watts")
Instances = resourceToSortCriteria("Instances")
SortByCPU = func (task *Task) float64 {return task.CPU}
SortByRAM = func (task *Task) float64 {return task.RAM}
SortByWatts = func (task *Task) float64 {return task.Watts}
)

View file

@ -4,7 +4,6 @@ import (
"github.com/mdesenfants/gokmeans"
"sort"
"log"
"reflect"
)
// Information about a cluster of tasks
@ -120,12 +119,9 @@ func labelAndOrder(clusters map[int][]Task, numberOfClusters int, taskObservatio
// Be able to sort an array of tasks based on any of the tasks' resources.
// Retrieve a sorter (same signature as 'Less' function in sort.Interface) for the given sorting criteria.
func TaskSorter(sc sortCriteria, tasks []Task) func (i, j int) bool {
type TasksToSort []Task
func (ts TasksToSort) TaskSorter(sb sortBy) func (i, j int) bool {
return func (i, j int) bool {
taskIFields := reflect.Indirect(reflect.ValueOf(tasks[i]))
tasksJFields := reflect.Indirect(reflect.ValueOf(tasks[j]))
resourceI := taskIFields.FieldByName(sc.String()).Float()
resourceJ := tasksJFields.FieldByName(sc.String()).Float()
return resourceI <= resourceJ
return sb(&ts[i]) <= sb(&ts[j])
}
}