1 回答

TA貢獻1943條經驗 獲得超7個贊
打包時間
import?"time"月、日、小時、分鐘、秒和納秒值可能超出其通常范圍,并將在轉換過程中標準化。例如,10 月 32 日轉換為 11 月 1 日。
這樣效率更高。它最大限度地減少了對包time
函數和方法的調用。
package main
import (
? ? "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 EDT
2019-06-22 15:00:00 -0400 EDT
一些基準:
BenchmarkNow-8? ? ? ? ? ? ? ? ? 31197811? ? ? ? ? ? 36.6 ns/op
BenchmarkTomorrowPeterSO-8? ? ? 29852671? ? ? ? ? ? 38.4 ns/op
BenchmarkTomorrowJens-8? ? ? ? ? 9523422? ? ? ? ? ?124 ns/op
bench_test.go:
package main
import (
? ? "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
? ? }
}
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報