managed_shared_memory.construct造成的性能损失 - 小众知识

managed_shared_memory.construct造成的性能损失

2022-07-28 04:41:58 苏内容
  标签:
阅读:1892

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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左右。因此在设计大数据量复制的应用程序时,最好不要频繁创建对象和析构对象,这点和进程内的程序开发是一致的。


扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1