Duration

1
2
3
4
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
  1. 它是基于 int64 定义的新类型

  2. 它的单位是纳秒

  3. 它最大能表示约290年,计算公式为 (2^63-1)/(10^9)/3600/24/365

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const (
minDuration Duration = -1 << 63
maxDuration Duration = 1<<63 - 1
)

// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
// second := time.Second
// fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
// seconds := 10
// fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
//
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
  1. 这里用了左移运算符 <<

  2. -1 << 63 相当于 -1*(2^63)

  3. 来看下左移运算符的作用

1
2
3
4
5
6
func Binary() {
fmt.Printf("%b\n", 4) // 输出100
fmt.Printf("%b\n", -1) // 输出-1 补码11111111
a := -1 << 3 // -8 补码11111000
fmt.Printf("%b\n", a) // 输出-1000
}
  1. go的左移都是带符号位的

  2. 计算机中的整数都是用补码表示的,补码能把正数和负数的运算转换为统一的操作