const (
H12Format = "2006/1/2/3/4.txt"
H24Format = "2006/1/2/15/4.txt"
)
func path(date time.Time) string {
if date.Hour() < 10 {
return date.Format(H12Format)
}
return date.Format(H24Format)
}
Unfortunately the go playground doesn't allow running tests and benchmarks.
The following code contain the previous solutions and mine with benchmark.
On my computer these are the result:
BenchmarkA-4 5000000 293 ns/op 32 B/op 1 allocs/op
BenchmarkB-4 5000000 380 ns/op 48 B/op 2 allocs/op
BenchmarkC-4 3000000 448 ns/op 56 B/op 4 allocs/op
To test it yourself copy the code locally and run it: go test -benchmem -run=XXX -bench=Benchmark
package format
import (
"fmt"
"testing"
"time"
)
const (
layout = "2006-01-02-3.txt"
layoutd = "2006-01-02-%d.txt"
H12Format = "2006/1/2/3/4.txt"
H24Format = "2006/1/2/15/4.txt"
)
func BenchmarkA(b *testing.B) {
for n := 0; n < b.N; n++ {
path(time.Now())
}
}
func BenchmarkB(b *testing.B) {
for n := 0; n < b.N; n++ {
fmtpath(time.Now())
}
}
func BenchmarkC(b *testing.B) {
for n := 0; n < b.N; n++ {
longpath(time.Now())
}
}
func path(date time.Time) string {
if date.Hour() < 10 {
return date.Format(H12Format)
}
return date.Format(H24Format)
}
func fmtpath(date time.Time) string {
return fmt.Sprintf(date.Format(layoutd), 4)
}
func longpath(date time.Time) string {
return fmt.Sprintf("%s-%d.txt", date.Format("2006-01-02"), date.Hour())
}