茴香豆的几种吃法之内存池队列使用方式

68 篇文章 3 订阅
20 篇文章 1 订阅

对比new delete 与使用容器管理内存队列release_x64模式:

new-delete 2000次:              0.2124 ms
std::deque 出入队2000次: 0.0699 ms

libuv 出入队2000次:           0.053 ms

std::mutex mutex1;
std::deque<const char *> bufs;
void testMem()
{
	Timer timer;
	timer.start();

	for (int i = 0; i < 2000; i++)
	{
		char * buf = new char[2048];
		delete buf;
	}

	double t = timer.stop_delta<Timer::ms>();
	cout << t << endl;

	/
	const char *p = "hello";
	timer.start();

	for (int i = 0; i < 2000; i++)
	{
		{
			std::lock_guard<std::mutex> lock(mutex1);
			bufs.push_back(p);
		}
		{
			std::lock_guard<std::mutex> lock(mutex1);
			bufs.pop_back();
		}

	}

	t = timer.stop_delta<Timer::ms>();
	cout << t << endl;
}

libuv模式:

#pragma once
#include <uv.h>
#include <mutex>
#include "../include/queue.h"

typedef struct mem_s
{
	mem_s()
	{
		buffer = new char[2048];
		nCap = 2048;
		nSize = 0;
	}
	~mem_s()
	{
		delete buffer;
	}
	void reset() { nSize = 0; }
	char *buffer;
	size_t nSize;
	size_t nCap;
	QUEUE node;
}mem_t;



class BufferQue
{
public:
	BufferQue()
	{
		QUEUE_INIT(&head);
		uv_mutex_init(&mutexQue);
	}

	~BufferQue()
	{
		uv_mutex_destroy(&mutexQue);
	}
	mem_t * getBuffer()
	{
		//std::lock_guard<std::mutex> guard(mutexQue);
		QUEUE * p;
		mem_t * ret;
		uv_mutex_lock(&mutexQue);

		p = QUEUE_HEAD(&head);
		if (p != &head)
		{
			QUEUE_REMOVE(p);
			ret = QUEUE_DATA(p, mem_t, node);
			assert(ret != nullptr);
			ret->reset();
		}
		else
		{
			ret = new mem_t();
		}
		uv_mutex_unlock(&mutexQue);
		return ret;
	}

	bool putBuffer(mem_t * buf)
	{
		//std::lock_guard<std::mutex> guard(mutexQue);
		if (buf == nullptr)
			return false;
		uv_mutex_lock(&mutexQue);
		QUEUE_INSERT_TAIL(&head, &(buf->node));
		uv_mutex_unlock(&mutexQue);
		return true;
	}

	private:
		QUEUE head;
		uv_mutex_t mutexQue;
		//std::mutex mutexQue;
		
};

void testBufferQue()
{
	BufferQue bufPool;
	mem_t * p = bufPool.getBuffer();
	bufPool.putBuffer(p);
	Timer timer;
	timer.start();
	for (int i = 0; i < 2000; i++)
	{
		mem_t * p = bufPool.getBuffer();
		bufPool.putBuffer(p);
	}

	double t = timer.stop_delta<Timer::ms>();
	cout << t << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值