managed_shared_memory.construct造成的性能损失

boost中的IPC进程间通信非常好用,可以直接在共享内存上创建对象,相当于new分配器,实测发现它的分配算法还是有点耗时。第一个测试代码仅仅分配一次,然后频繁的复制,每秒钟可以复制4200次左右。

// HelloBoostIPC.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <cstdlib> //std::system
#include <cstddef>
#include <cassert>
#include <utility>
#include <string>
#include <Windows.h>

using namespace std;
using namespace boost;
using namespace boost::interprocess;  

char dummy[1280*720*3];

class VideoFrame
{
public:
	int width;
	int height;
	boost::interprocess::interprocess_mutex mutex;
	char data[1280*720*3];
};

int _tmain(int argc, _TCHAR* argv[])
{
	int begin, end, n=0;

	struct shm_remove
	{
		shm_remove() { shared_memory_object::remove("MySharedMemory"); }
		~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
	} remover;

	managed_shared_memory segment(create_only, "MySharedMemory", sizeof(VideoFrame)*24);
	VideoFrame *frame = segment.construct<VideoFrame>("frame")();
	while(true)
	{
		if(n==0)
		{
			begin = ::GetTickCount();
		}
		frame->width = 1280;
		frame->height = 720;
		scoped_lock<interprocess_mutex> lock(frame->mutex);
		memcpy(frame->data, dummy, sizeof(dummy));
		n++;
		if(n==1000)
		{
			end = ::GetTickCount();
			float t = (end-begin)/1000.0f;
			int rate = (int)(1000/t);
			printf("write rate=%d\r\n", rate);
			n = 0;
		}
		
	}
	segment.destroy<VideoFrame>("frame");

	return 0;
}

 

如果更换成在循环内部分配内存,再释放,则复制频率下降到3200左右。因此在设计大数据量复制的应用程序时,最好不要频繁创建对象和析构对象,这点和进程内的程序开发是一致的。

转载于:https://www.cnblogs.com/swnuwangyun/p/4861452.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值