Skip to content

Instantly share code, notes, and snippets.

@davyzhang
Created March 5, 2013 11:17
Show Gist options
  • Save davyzhang/5089624 to your computer and use it in GitHub Desktop.
Save davyzhang/5089624 to your computer and use it in GitHub Desktop.
Use cache to reduce the call of fmt.Sprintf() to speed up the formating time to string operation
/*
Use cache to reduce the call of fmt.Sprintf() to speed up the formating time to string operation
*/
package timeutil
import (
"fmt"
"time"
)
const (
P_YMD = 0
P_H = 9
P_M = 12
P_S = 15
P_MS = 18
)
const (
U_YMD = 1 << iota
U_H
U_M
U_S
U_MS
)
type fmtCache struct {
//cached value for compare
year,
month,
day,
hour,
minute,
sec,
millisec int
buf []byte
}
func NewCache() *fmtCache {
c := &fmtCache{buf: make([]byte, 21)}
copy(c.buf, "00000000 00:00:00.000")
c.refresh(time.Now())
return c
}
func (fc *fmtCache) refresh(t time.Time) int {
y, M, d := t.Date()
h, m, s := t.Clock()
n := t.Nanosecond()
var flag int
if y != fc.year || int(M) != fc.month || d != fc.day {
fc.year = y
fc.month = int(M)
fc.day = d
copy(fc.buf[:P_YMD+8], fmt.Sprintf("%d%02d%02d", y, M, d))
flag |= U_YMD
// fmt.Printf("YMD changed %d%02d%02d\n", fc.year, fc.month, fc.day)
}
if h != fc.hour {
fc.hour = h
copy(fc.buf[P_H:P_H+2], fmt.Sprintf("%02d", h))
flag |= U_H
// fmt.Printf("hour changed %02d\n", fc.hour)
}
if m != fc.minute {
fc.minute = m
copy(fc.buf[P_M:P_M+2], fmt.Sprintf("%02d", m))
flag |= U_M
// fmt.Printf("minute changed %02d\n", fc.minute)
}
if s != fc.sec {
fc.sec = s
copy(fc.buf[P_S:P_S+2], fmt.Sprintf("%02d", s))
flag |= U_S
// fmt.Printf("sec changed %02d\n", fc.minute)
}
if n != fc.millisec*1000*1000 {
fc.millisec = n / 1000 / 1000
copy(fc.buf[P_MS:P_MS+3], fmt.Sprintf("%03d", fc.millisec))
flag |= U_MS
// fmt.Printf("ms changed %02d\n", fc.millisec)
}
return flag
}
func (fc *fmtCache) Full(t time.Time) string { //(year,month,day,hour,minute,sec,ms string) {
fc.refresh(t)
return string(fc.buf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment