| 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 request |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"math" |
| 22 |
"time" |
| 23 |
) |
| 24 |
|
| 25 |
// SeatSeconds is a measure of work, in units of seat-seconds, using a fixed-point representation. |
| 26 |
// `SeatSeconds(n)` represents `n/ssScale` seat-seconds. |
| 27 |
// The `ssScale` constant is private to the implementation here, |
| 28 |
// no other code should use it. |
| 29 |
type SeatSeconds uint64 |
| 30 |
|
| 31 |
// MaxSeatsSeconds is the maximum representable value of SeatSeconds |
| 32 |
const MaxSeatSeconds = SeatSeconds(math.MaxUint64) |
| 33 |
|
| 34 |
// MinSeatSeconds is the lowest representable value of SeatSeconds |
| 35 |
const MinSeatSeconds = SeatSeconds(0) |
| 36 |
|
| 37 |
// SeatsTimeDuration produces the SeatSeconds value for the given factors. |
| 38 |
// This is intended only to produce small values, increments in work |
| 39 |
// rather than amount of work done since process start. |
| 40 |
func SeatsTimesDuration(seats float64, duration time.Duration) SeatSeconds { |
| 41 |
return SeatSeconds(int64(math.Round(seats * float64(duration/time.Nanosecond) / (1e9 / ssScale)))) |
| 42 |
} |
| 43 |
|
| 44 |
// ToFloat converts to a floating-point representation. |
| 45 |
// This conversion may lose precision. |
| 46 |
func (ss SeatSeconds) ToFloat() float64 { |
| 47 |
return float64(ss) / ssScale |
| 48 |
} |
| 49 |
|
| 50 |
// DurationPerSeat returns duration per seat. |
| 51 |
// This division may lose precision. |
| 52 |
func (ss SeatSeconds) DurationPerSeat(seats float64) time.Duration { |
| 53 |
return time.Duration(float64(ss) / seats * (float64(time.Second) / ssScale)) |
| 54 |
} |
| 55 |
|
| 56 |
// String converts to a string. |
| 57 |
// This is suitable for large as well as small values. |
| 58 |
func (ss SeatSeconds) String() string { |
| 59 |
const div = SeatSeconds(ssScale) |
| 60 |
quo := ss / div |
| 61 |
rem := ss - quo*div |
| 62 |
return fmt.Sprintf("%d.%08dss", quo, rem) |
| 63 |
} |
| 64 |
|
| 65 |
const ssScale = 1e8 |