包装时间
import "time"月,日,小时,分钟,秒和nsec值可能超出其通常范围,并将在转换过程中进行归一化。例如,10月32日转换为11月1日。
这样更有效。它最大程度地减少了对包
time函数和方法的调用。
package mainimport ( "fmt" "time")func main() { now := time.Now() fmt.Println(now.Round(0)) yyyy, mm, dd := now.Date() tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location()) fmt.Println(tomorrow)}输出:
2019-06-21 16:23:06.525478162 -0400 EDT2019-06-22 15:00:00 -0400 EDT
一些基准:
BenchmarkNow-8 31197811 36.6 ns/opBenchmarkTomorrowPeterSO-8 29852671 38.4 ns/opBenchmarkTomorrowJens-8 9523422124 ns/op
bench_test.go:
package mainimport ( "testing" "time")func BenchmarkNow(b *testing.B) { for N := 0; N < b.N; N++ { now := time.Now() _ = now }}var now = time.Now()func BenchmarkTomorrowPeterSO(b *testing.B) { for N := 0; N < b.N; N++ { // now := time.Now() yyyy, mm, dd := now.Date() tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location()) _ = tomorrow }}func BenchmarkTomorrowJens(b *testing.B) { for N := 0; N < b.N; N++ { // now := time.Now() tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, now.Location()).AddDate(0, 0, 1) _ = tomorrow }}


