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左右。因此在设计大数据量复制的应用程序时,最好不要频繁创建对象和析构对象,这点和进程内的程序开发是一致的。