1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package helper 18 19 // FunctionShape represents a collection of FunctionShapePoint. 20 type FunctionShape []FunctionShapePoint 21 22 // FunctionShapePoint represents a shape point. 23 type FunctionShapePoint struct { 24 // Utilization is function argument. 25 Utilization int64 26 // Score is function value. 27 Score int64 28 } 29 30 // BuildBrokenLinearFunction creates a function which is built using linear segments. Segments are defined via shape array. 31 // Shape[i].Utilization slice represents points on "Utilization" axis where different segments meet. 32 // Shape[i].Score represents function values at meeting points. 33 // 34 // function f(p) is defined as: 35 // 36 // shape[0].Score for p < shape[0].Utilization 37 // shape[n-1].Score for p > shape[n-1].Utilization 38 // 39 // and linear between points (p < shape[i].Utilization) 40 func BuildBrokenLinearFunction(shape FunctionShape) func(int64) int64 { 41 return func(p int64) int64 { 42 for i := 0; i < len(shape); i++ { 43 if p <= int64(shape[i].Utilization) { 44 if i == 0 { 45 return shape[0].Score 46 } 47 return shape[i-1].Score + (shape[i].Score-shape[i-1].Score)*(p-shape[i-1].Utilization)/(shape[i].Utilization-shape[i-1].Utilization) 48 } 49 } 50 return shape[len(shape)-1].Score 51 } 52 } 53