cron
cron copied to clipboard
algorithm optimization
code
for {
// Determine the next entry to run.
sort.Sort(byTime(c.entries))
....
}
problem
method sort.Sort will be called every time in the for loop.
proposal
use min heap replace c.entries, in this way each add is in order do not need to sort.
When c.entries is already in order and add a new task, sort.Sort will use a suitable algorithm automatically to resort c.entries. this suitable algorithm is not less than heap.
When c.entries is already in order and add a new task, sort.Sort will use a suitable algorithm automatically to resort c.entries. this suitable algorithm is not less than heap.
func main() {
arr := make([]int, 10000)
x := int(math.Sqrt(float64(len(arr))))
for i := 0; i < 1e5; i++ { // 0.20s user 0.12s system 154% cpu 0.206 total
for j := 0; j <= x; j++ { // log n
}
}
for i := 0; i < 1e5; i++ { // 8.99s user 0.19s system 100% cpu 9.148 total
sort.Ints(arr)
}
}