forked from AliyunContainerService/spot-instance-advisor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.go
86 lines (70 loc) · 2 KB
/
sort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
log "github.com/Sirupsen/logrus"
ecsService "github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"math"
"time"
)
// data structure of instance prices
type InstancePrice struct {
ecsService.InstanceType
ZoneId string
PricePerCore float64
Price string
Discount float64
Possibility float64
}
// sorted structure of
type SortedInstancePrices []InstancePrice
func (sp SortedInstancePrices) Len() int {
return len(sp)
}
func (sp SortedInstancePrices) Less(i, j int) bool {
return sp[i].PricePerCore < sp[j].PricePerCore
}
func (sp SortedInstancePrices) Swap(i, j int) {
sp[i], sp[j] = sp[j], sp[i]
}
func CreateInstancePrice(meta ecsService.InstanceType, zoneId string, prices []ecsService.SpotPriceType) InstancePrice {
latestPrice := FindLatestPrice(prices)
ip := InstancePrice{
InstanceType: meta,
ZoneId: zoneId,
PricePerCore: latestPrice.SpotPrice / float64(meta.CpuCoreCount),
Price: fmt.Sprintf("%f", latestPrice.SpotPrice),
Discount: 10 * latestPrice.SpotPrice / latestPrice.OriginPrice,
Possibility: GetPossibility(prices),
}
return ip
}
func FindLatestPrice(prices []ecsService.SpotPriceType) ecsService.SpotPriceType {
var latestPrice ecsService.SpotPriceType
for _, price := range prices {
if latestPrice.Timestamp == "" {
latestPrice = price
} else {
latestDate, err := time.Parse(time.RFC3339, latestPrice.Timestamp)
if err != nil {
log.Panicf("Time format is not valid,because of %v", err)
}
currentDate, err := time.Parse(time.RFC3339, price.Timestamp)
if err != nil {
log.Panicf("Time format is not valid,because of %v", err)
}
if latestDate.Before(currentDate) {
latestPrice = price
}
}
}
return latestPrice
}
func GetPossibility(prices []ecsService.SpotPriceType) float64 {
variance := 0.0
sigma := 0.0
for _, price := range prices {
variance += math.Pow((price.SpotPrice - 0.1*price.OriginPrice), 2)
}
sigma = math.Sqrt(variance / float64(len(prices)))
return sigma
}