Skip to content

Commit

Permalink
using sync.Pool for bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
wongoo committed Jan 9, 2020
1 parent fa171e5 commit 967e5af
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 50 deletions.
51 changes: 6 additions & 45 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"os"
"runtime"
"sync"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -41,7 +40,6 @@ const (
var (
Level = LevelInfo
output io.Writer = os.Stdout
lock sync.Mutex
flag int
)

Expand Down Expand Up @@ -182,55 +180,26 @@ func Panicln(a ...interface{}) {
}

var (
poolSize int32 = 128
poolIndex int32 = -1
poolBuffers = make([][]byte, poolSize)
poolFlag = make([]int32, poolSize)
defaultBuffer []byte
bytesPool = sync.Pool{New: func() interface{} {
b := make([]byte, 1024)
return &b
}}
)

// SetPoolSize set pool size
func SetPoolSize(s int) {
size := int32(s)

if size == poolSize {
return
}

if size < poolSize {
fmt.Println("not support to shrink logger buffer pool size")
return
}

poolBuffers = make([][]byte, size)
poolFlag = make([]int32, size)
poolSize = int32(cap(poolBuffers))
}

// WriteLog write log data
func WriteLog(tag, s string) {
var (
pc uintptr
fileName string
funcName string
line int
index int32
callerOk bool
poolOK bool
buf []byte
)

t := time.Now()

index = atomic.AddInt32(&poolIndex, 1) % poolSize
poolOK = atomic.CompareAndSwapInt32(&poolFlag[index], 0, 1)

if poolOK {
buf = poolBuffers[index][:0]
} else {
lock.Lock()
buf = defaultBuffer[:0]
}
buf = (*(bytesPool.Get().(*[]byte)))[:0]

year, month, day := t.Date()
appendNumber(&buf, year, 4)
Expand Down Expand Up @@ -291,17 +260,9 @@ func WriteLog(tag, s string) {
buf = append(buf, '\n')
}

if poolOK {
lock.Lock()
}

_, _ = output.Write(buf)

lock.Unlock()

if poolOK {
atomic.StoreInt32(&poolFlag[index], 0)
}
bytesPool.Put(&buf)
}

// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
Expand Down
5 changes: 0 additions & 5 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,6 @@ func TestSetWriter(t *testing.T) {
}
}

func TestSetPoolSize(t *testing.T) {
SetPoolSize(512)
SetPoolSize(128)
}

func TestTimeFormat(t *testing.T) {
now := time.Now()
fmt.Println(now.Format("20060102 15:04:05.999"))
Expand Down

0 comments on commit 967e5af

Please sign in to comment.