memory pool 的高效实现(代码)

mpool.h

mpool.c

 

 

BenchMark

#include <vector>

#include <febird/c/mpool.h>
#include <febird/profiling.h>

void bench(int n)
{
	using namespace std;

	std::allocator<sample_data> stdal;
	struct fixed_mpool fmp = {0};
	fmp.cell_size = sizeof(sample_data);
	fmp.chunk_size = 8192;
	fmp.nChunks = 1024;
	fixed_mpool_init(&fmp);

	febird::profiling prof;

	vector<sample_data*> vp0(n), vp1(n);

	long long t0, t1, t2, t3, t4, t5, t6;
	t0 = prof.current();
	for (int i = 0; i+3 < n; i+=4)
	{
		vp0[i+0] = stdal.allocate(1);
		vp0[i+1] = stdal.allocate(1);
		vp0[i+2] = stdal.allocate(1);
		vp0[i+3] = stdal.allocate(1);
	}
	t1 = prof.current();
	for (int i = 0; i+3 < n; i+=4)
	{
		vp1[i+0] = (sample_data*)fixed_mpool_alloc(&fmp);
		vp1[i+1] = (sample_data*)fixed_mpool_alloc(&fmp);
		vp1[i+2] = (sample_data*)fixed_mpool_alloc(&fmp);
		vp1[i+3] = (sample_data*)fixed_mpool_alloc(&fmp);
	}
	t2 = prof.current();
	for (int i = 0; i+3 < n; i+=4)
	{
		stdal.deallocate(vp0[i+0], sizeof(sample_data));
		stdal.deallocate(vp0[i+1], sizeof(sample_data));
		stdal.deallocate(vp0[i+2], sizeof(sample_data));
		stdal.deallocate(vp0[i+3], sizeof(sample_data));
	}
	t3 = prof.current();
	for (int i = 0; i+3 < n; i+=4)
	{
		fixed_mpool_free(&fmp, vp1[i+0]);
		fixed_mpool_free(&fmp, vp1[i+1]);
		fixed_mpool_free(&fmp, vp1[i+2]);
		fixed_mpool_free(&fmp, vp1[i+3]);
	}
	t4 = prof.current();
	for (int i = 0; i < n; ++i)
	{
		stdal.deallocate(stdal.allocate(1), sizeof(sample_data));
	}
	t5 = prof.current();
	for (int i = 0; i < n; ++i)
	{
		fixed_mpool_free(&fmp, fixed_mpool_alloc(&fmp));
	}
	t6 = prof.current();

	printf("alloc[std=%lld, my=%lld, std/my=%f], free[std=%lld, my=%lld, std/my=%f], alloc+free[std=%lld, my=%lld, std/my=%f]\n"
		, prof.us(t0,t1), prof.us(t1,t2), (double)prof.us(t0,t1)/prof.us(t1,t2)
		, prof.us(t2,t3), prof.us(t3,t4), (double)prof.us(t2,t3)/prof.us(t3,t4)
		, prof.us(t4,t5), prof.us(t5,t6), (double)prof.us(t4,t5)/prof.us(t5,t6)
		);

	fixed_mpool_destroy(&fmp);
}

int main(int argc, char* argv[])
{
	bench(1000000);
	return 0;
}

 

Windows7 + visual C++ 2008

 

time in us

std::allocator(new/delete)

fixed_mpool

fast ratio

alloc

93901

15416

6.091139

free

70657

7374

9.581909

alloc+free

131739

9297

14.170055

Linux

uname:

Linux 2.6.9-78.ELsmp #1 SMP Wed Jul 9 15:46:26 EDT 2008 x86_64 x86_64 x86_64 GNU/Linux

 

time in us

std::allocator(pooled)

fixed_mpool

fast ratio

alloc

92779

26734

3.470450

free

42564

17224

2.471203

alloc+free

50089

9088

5.511554

 

你可能感兴趣的:(多线程,C++,c,C#,Google)