当前位置: 首页 > 工具软件 > Go Buffer > 使用案例 >

golang buffer池子

计承德
2023-12-01

使用buffer池子

// 声明buffer var numCalcsCreated int32
var numCalcsCreatedBuff int32
func CreateBuffer() interface{} {
	atomic.AddInt32(&numCalcsCreatedBuff, 1)
	return new(bytes.Buffer)
}

func BufferPool() *sync.Pool {
	// 创建实例
	return &sync.Pool{
		New: CreateBuffer,
	}
}



func Benchmark_byte_buffer(t *testing.B)  {
	// 声明一个 buffer
	t.StopTimer()

	bufferPool := BufferPool()
	// 启动的buff池子:1845,花销时间,10.92787875s
	//Benchmark_byte_buffer-8   	       1	10927927958 ns/op
	var ts  sync.WaitGroup
	t.StartTimer()
	start := time.Now()
	for i := 1; i<=100000000 ; i++{
		ts.Add(1)
		go func(i int ) {
			ts.Done()
			dataBuff := bufferPool.Get().(*bytes.Buffer)
			var lens uint64 // 占用8个字节

			// 将 int64 写入 buffer
			if err := binary.Write(dataBuff,binary.LittleEndian,uint64(i));err != nil {
				t.Log(err)
				return
			}

			lens = 5
			//将 int64 写入 buffer
			if err := binary.Write(dataBuff,binary.LittleEndian,lens);err != nil {
				t.Log(err)
				return
			}
			// data写入数据中 buffer 两个中文字占用6个字节
			if err := binary.Write(dataBuff,binary.LittleEndian,[]byte("你好"));err != nil {
				t.Log(err)
				return
			}

			byteRes := dataBuff.Bytes()
			dataBuff.Reset()
			bufferPool.Put(dataBuff)

			resI := binary.LittleEndian.Uint64(byteRes)
			_ = resI

		}(i)
		i++

	}

	ts.Wait()
	cost := time.Since(start)
	t.Logf("启动的buff池子:%d,花销时间,%v",numCalcsCreatedBuff,cost)

}

不使用buffer池子

func Benchmark_byte_no_buffer(t *testing.B)  {
	// 声明一个 buffer

	//启动的buff池子:0,花费时间:12.557962583s
	//Benchmark_byte_no_buffer-8   	       1	12558026000 ns/op

	t.StopTimer()
	var ts  sync.WaitGroup
	t.StartTimer()
	startNow := time.Now()
	for i := 1; i<=100000000 ; i++{
		ts.Add(1)
		go func(i int ) {
			ts.Done()
			dataBuff := new(bytes.Buffer)
			var lens uint64 // 占用8个字节
			// 将 int64 写入 buffer
			if err := binary.Write(dataBuff,binary.LittleEndian,uint64(i));err != nil {
				t.Log(err)
				return
			}

			lens = 5
			//将 int64 写入 buffer
			if err := binary.Write(dataBuff,binary.LittleEndian,lens);err != nil {
				t.Log(err)
				return
			}

			// data写入数据中 buffer 两个中文字占用6个字节
			if err := binary.Write(dataBuff,binary.LittleEndian,[]byte("你好"));err != nil {
				t.Log(err)
				return
			}
			byteRes := dataBuff.Bytes()
			resI := binary.LittleEndian.Uint64(byteRes)
			//t.Log(resI)
			_ = resI


		}(i)
		i++

	}

	ts.Wait()
	cost := time.Since(startNow)
	t.Logf("启动的buff池子:%d,花费时间:%v",numCalcsCreatedBuff,cost)

}

 类似资料: