c++ - C++对象应该如何序列化?

标签 c++ serialization ipc mpi

我们正在做一个关于高性能计算的项目,它使用 MPI 作为并行计算框架。只有少数算法已经在遗留平台上实现。我们所做的是将原来的串行算法改写为基于MPI的并行版本。

我遇到这样的性能问题:基于MPI运行并行算法时,多进程之间的通信开销很大。进程间通信由三个步骤组成:

  1. 进程 A 将一些 C++ 对象序列化为二进制格式。
  2. 进程A通过MPI向进程B发送二进制格式的数据。
  3. 进程 B 将二进制格式数据反序列化为 C++ 对象。

我们发现这些通信步骤,尤其是序列化/反序列化步骤,花费了大量时间。我们如何解决这个性能问题?

顺便说一下,在我们的 C++ 代码中,我们使用了很多 STL,它比类 C 的结构更复杂。

附言我现在正在通过编写代码遍历对象的所有字段并将它们按顺序复制到字节数组中来执行此操作(序列化)。

为了演示我在做什么,这里有一个代码片段。请注意,这只是一个单一的特征构建过程:

sic::GeometryFeature *ptFeature =
    (GeometryFeature *) outLayer->getFeature(iFeature);
sic::Geometry* geom = ptFeature->getGeometry();
std::string geomClassName = geom->getClassName();

sic::Geometry* ptGeom = geom;
unsigned char *wkbBuffer = NULL;
OGRGeometry * gtGeom = NULL;
if (geomClassName == "Point") {
    ptGeom = new sic::MultiPoint();
    ((sic::MultiPoint *) ptGeom)->insert(geom);
    gtGeom = new OGRMultiPoint();
    int wkbSize = ((sic::MultiPoint *) ptGeom)->WkbSize();
    wkbBuffer = (unsigned char *) malloc(wkbSize);
    ((sic::GeometryCollection *) ptGeom)->exportToWkb(sic::wkbNDR,
        wkbBuffer, wkbMultiPoint);
}
} else if (...) {
    ......
}
gtGeom->importFromWkb(wkbBuffer);
free(wkbBuffer);
assert(gtGeom);
OGRFeature * poFeature = OGRFeature::CreateFeature(
     poLayer->GetLayerDefn());
poFeature->SetGeometry(gtGeom);

还有更多关于我在做什么序列化对象:

unsigned char *bytes = (unsigned char *) malloc(size);
    size_t offset = 0;

    size_t type_size = sizeof(OGRwkbGeometryType);
    OGRwkbGeometryType type = layer->GetGeomType();
    memcpy(bytes + offset, &type, type_size);
    offset += type_size;

    size_t count_size = sizeof(int);
    int count = layer->GetFeatureCount();
    memcpy(bytes + offset, &count, count_size);
    offset += count_size;

    layer->ResetReading();
    for (OGRFeature *feature = layer->GetNextFeature(); feature != NULL;
            feature = layer->GetNextFeature()) {
        OGRGeometry *geometry = feature->GetGeometryRef();
        if (geometry) {
            geometry->exportToWkb(wkbNDR, bytes + offset);
            offset += geometry->WkbSize();
        } else {
            (*(int *) (bytes + type_size))--;
        }
        OGRFeature::DestroyFeature(feature);
    }

    return bytes;

任何评论将不胜感激。谢谢!

最佳答案

(Brian 的回答是提供帮助您使用库...他是一位非常有经验的程序员 - 听起来值得一试。)

另外,我查看了您的代码 - 有很多临时缓冲区、新/malloc 分配、sizeof 的使用等。所以我想我会说明一种“快速、简单但不错”的清理方法 - 足够了希望能让你开始......

首先创建一个二进制流类型,它分解并隐藏了很多低级工作:

#include <arpa/inet.h> // for htonl/s, ntoh/s
#include <endian.h> // for htonbe64, if you have it...

#include <iostream>
#include <string>
#include <map>

// support routines - use C++ overloading to polymorphically dispatch htonl/s

// uint64_t hton(uint64_t n) { return htonbe64(n); }
uint32_t hton(uint32_t n) { return htonl(n); }
uint16_t hton(uint16_t n) { return htons(n); }

// there are no "int" versions - this is ugly but effective...
uint32_t hton(int32_t n) { return htonl(n); }
uint16_t hton(int16_t n) { return htons(n); }

// uint64_t ntoh(uint64_t n) { return betoh64(n); }
uint32_t ntoh(uint32_t n) { return ntohl(n); }
uint16_t ntoh(uint16_t n) { return ntohl(n); }

template <typename OStream>
class Binary_OStream : public OStream
{
  public:
    typedef Binary_OStream This;

    This& write(const char* s, std::streamsize n)
    {
        OStream::write(s, n);
        return *this;
    }

    template <typename T>
    This& rawwrite(const T& t)
    {
        static_cast<OStream&>(*this) << '[' << sizeof t << ']';
        return write((const char*)&t, sizeof t);
    }

    template <typename T>
    This& hton(T h)
    {
        T n = ::hton(h);
        return rawwrite(n);
    }

    // conversions for inbuilt & Standard-library types...

    friend This& operator<<(This& bs, bool x) { return bs << (x ? 'T' : 'F'); }
    friend This& operator<<(This& bs, int8_t x) { return bs << x; }
    friend This& operator<<(This& bs, uint8_t x) { return bs << x; }
    friend This& operator<<(This& bs, int16_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, uint16_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, int32_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, uint32_t x) { return bs.hton(x); }

    friend This& operator<<(This& bs, double d) { return bs.rawwrite(d); }

    friend This& operator<<(This& bs, const std::string& x)
    {
        bs << x.size();
        return bs.write(x.data(), x.size());
    }

    template <typename K, typename V, typename A>
    friend This& operator<<(This& bs, const std::map<K, V, A>& m)
    {
        typedef typename std::map<K, V, A>::const_iterator It;

        bs << m.size();

        for (It it = m.begin(); it != m.end(); ++it)
            bs << it->first << it->second;

        return bs;
    }

    // add any others you want...
};

创建用户定义的二进制可序列化类型...

// for your own objects...    
struct Object
{
    Object(const std::string& s, double x) : s_(s), x_(x) { }

    std::string s_;
    double x_;

    // specify how you want binary serialisation performed (which fields/order etc)
    template <typename T>
    friend Binary_OStream<T>& operator<<(Binary_OStream<T>& os, const Object& o)
    {
        return os << o.s_ << o.x_;
    }
};

示例用法:

#include <iomanip>
#include <sstream>

// support routines just to help you observe/debug the serialisation...

std::string printable(char c)
{
    std::ostringstream oss;
    if (isprint(c))
        oss << c;
    else
        oss << "\\x" << std::hex << std::setw(2) << std::setfill('0')
            << (int)(uint8_t)c << std::dec;
    return oss.str();
}

std::string printable(const std::string& s)
{
    std::string result;
    for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
        result += printable(*i);
    return result;
}

int main()
{
    {
        Binary_OStream<std::ostringstream> bs;

        Object o("pi", 3.14);

        bs << o;

        std::cout << "serialised to '" << printable(bs.str()) << "'\n";
    }

    {
        Binary_OStream<std::ostringstream> bs;

        std::map<int, std::string> m;
        m[0] = "zero";
        m[1] = "one";
        m[2] = "two";
        bs << m;

        std::cout << "serialised to '" << printable(bs.str()) << "'\n";
    }
}

下一步是创建一个 Binary_IStream - 它与上面非常相似。 ( boost 通过使用 '%' 运算符而不是传统的 <<>> 来减少工作量,这样同一个函数就可以指定用于序列化和反序列化的字段。)

实现笔记/想法:

  • 如果您愿意,可以从 Binary_Stream 中删除模板参数,并让构造函数将任意 std::ostream& 存储到 private 成员变量中,然后将所有流操作发送到该数据成员。
    • 这样做的好处是可以最大限度地减少因不同流类型的实例化而导致的代码膨胀,允许实现对翻译单元隐藏并在以后链接(有助于在大型项目中缩短编译时间),并且让您只需附加一个 Binary_Stream随时转到任何现有流(如果有人向您传递一个预先存在的流,那就太好了)。
    • “缺点”是您必须显式转发到您希望 ostream 用户可以访问的任何其他 Binary_Stream 成员函数(更多控制但乏味),或者提供(不太方便/优雅?)std::ostream& stream() { return s_; } 样式访问器.

关于c++ - C++对象应该如何序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17699918/

相关文章:

c++ - QMainWindow 在 show() 后立即关闭

c++ - 组合可编辑 C++

android - 包裹中 `createTypedArrayList()`和 `readTypedList()`的区别

javascript - 使用 AJAX 序列化日期

linux - 如何确保我的 child 先执行,然后是 parent ?

c++ - 如何使用 scons 生成带有调试信息的 MSVC 解决方案?

c++ - 如何设置两个 vector<unique_ptr<...>> 彼此相等?

c++ - Boost 反序列化期间出错

android - 从另一个 Context 向 HostApduService 传递信息

c++ - msgsnd 参数无效