-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_value.go
More file actions
93 lines (80 loc) · 2.04 KB
/
Copy pathdiff_value.go
File metadata and controls
93 lines (80 loc) · 2.04 KB
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
87
88
89
90
91
92
93
package chronos
import (
"strconv"
)
// DiffValue 差值,单位:纳秒
type DiffValue int64
const (
nanosPerMicro = 1000
nanosPerMilli = 1000 * nanosPerMicro
nanosPerSec = 1000 * nanosPerMilli
nanosPerMin = 60 * nanosPerSec
nanosPerHour = 60 * nanosPerMin
)
// Nanoseconds 转成纳秒
func (d DiffValue) Nanoseconds() int64 {
return int64(d)
}
// Microseconds 转成微秒
func (d DiffValue) Microseconds() int64 {
return int64(d) / nanosPerMicro
}
// Milliseconds 转成毫秒
func (d DiffValue) Milliseconds() int64 {
return int64(d) / nanosPerMilli
}
// Seconds 转成秒
func (d DiffValue) Seconds() int64 {
return int64(d) / nanosPerSec
}
// Minutes 转成分
func (d DiffValue) Minutes() int64 {
return int64(d) / nanosPerMin
}
// Hours 转成小时
func (d DiffValue) Hours() int64 {
return int64(d) / nanosPerHour
}
// String 返回人类可读的时间差格式,零差值返回 "0ns"
func (d DiffValue) String() string {
if d == 0 {
return "0ns"
}
absNanos := int64(d)
if absNanos < 0 {
absNanos = -absNanos
}
sign := ""
if d < 0 {
sign = "-"
}
var formatTime = func(value int, unit string) string {
if value == 0 {
return ""
}
return strconv.Itoa(value) + unit
}
switch {
case absNanos < nanosPerMicro:
return sign + formatTime(int(absNanos), "ns")
case absNanos < nanosPerMilli:
v := int(absNanos / nanosPerMicro)
return sign + formatTime(v, "μs")
case absNanos < nanosPerSec:
ms := int(absNanos / nanosPerMilli)
return sign + formatTime(ms, "ms")
case absNanos < nanosPerMin:
sec := int(absNanos / nanosPerSec)
return sign + formatTime(sec, "s")
case absNanos < nanosPerHour:
val := int(absNanos / nanosPerMin)
sec := int(absNanos%nanosPerMin) / nanosPerSec
return sign + formatTime(val, "m") + formatTime(sec, "s")
default:
hours := int(absNanos / nanosPerHour)
remaining := absNanos % nanosPerHour
val := int(remaining / nanosPerMin)
sec := int(remaining%nanosPerMin) / nanosPerSec
return sign + formatTime(hours, "h") + formatTime(val, "m") + formatTime(sec, "s")
}
}