github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/cos/math.go (about) 1 // Package cos provides common low-level types and utilities for all aistore projects 2 /* 3 * Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. 4 */ 5 package cos 6 7 import ( 8 "time" 9 10 "github.com/NVIDIA/aistore/cmn/debug" 11 ) 12 13 type Bits uint8 14 15 func MinTime(a, b time.Time) time.Time { 16 if a.Before(b) { 17 return a 18 } 19 return b 20 } 21 22 // Min returns min value from given ints. 23 func Min(xs ...int) int { 24 debug.Assert(len(xs) > 0) 25 if len(xs) == 1 { 26 return xs[0] 27 } 28 if len(xs) == 2 { 29 if xs[0] < xs[1] { 30 return xs[0] 31 } 32 return xs[1] 33 } 34 return Min(xs[0], Min(xs[1:]...)) 35 } 36 37 // Max returns max value from given ints. 38 func Max(xs ...int) int { 39 debug.Assert(len(xs) > 0) 40 if len(xs) == 1 { 41 return xs[0] 42 } 43 if len(xs) == 2 { 44 if xs[0] > xs[1] { 45 return xs[0] 46 } 47 return xs[1] 48 } 49 return Max(xs[0], Max(xs[1:]...)) 50 } 51 52 func Abs(a int) int { 53 if a < 0 { 54 return -a 55 } 56 return a 57 } 58 59 func AbsI64(a int64) int64 { 60 if a < 0 { 61 return -a 62 } 63 return a 64 } 65 66 func DivCeil(a, b int64) int64 { 67 d, r := a/b, a%b 68 if r > 0 { 69 return d + 1 70 } 71 return d 72 } 73 74 func DivRound(a, b int64) int64 { return (a + b/2) / b } 75 func DivRoundU64(a, b uint64) uint64 { return (a + b/2) / b } 76 77 // CeilAlign returns smallest number bigger or equal to val, which is divisible by align 78 func CeilAlign(val, align uint) uint { 79 mod := val % align 80 if mod != 0 { 81 val += align - mod 82 } 83 return val 84 } 85 86 func CeilAlignInt64(val, align int64) int64 { 87 mod := val % align 88 if mod != 0 { 89 val += align - mod 90 } 91 return val 92 } 93 94 // FastLog2 returns floor(log2(c)) 95 func FastLog2(c uint64) uint { 96 for i := uint(0); ; { 97 if c >>= 1; c == 0 { 98 return i 99 } 100 i++ 101 } 102 } 103 104 func FastLog2Ceil(c uint64) uint { 105 if c == 0 { 106 return 0 107 } 108 return FastLog2(c-1) + 1 109 } 110 111 func (b *Bits) Set(flag Bits) { x := *b; x |= flag; *b = x } 112 func (b *Bits) Clear(flag Bits) { x := *b; x &^= flag; *b = x } 113 func (b *Bits) Toggle(flag Bits) { x := *b; x ^= flag; *b = x } 114 func (b *Bits) Has(flag Bits) bool { return *b&flag != 0 } 115 116 func Ratio(high, low, curr int64) float32 { 117 Assert(high > low && high <= 100 && low > 0) 118 if curr <= low { 119 return 0 120 } 121 if curr >= high { 122 return 1 123 } 124 return float32(curr-low) / float32(high-low) 125 } 126 127 func RatioPct(high, low, curr int64) int64 { 128 Assert(high > low && high <= 100 && low > 0) 129 if curr <= low { 130 return 0 131 } 132 if curr >= high { 133 return 100 134 } 135 return (curr - low) * 100 / (high - low) 136 }