将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么



我有两个进程p1p2p1在 x86 中构建,p2在 x64 平台中构建,使用 (Visual Studio 2013/MFC/C++(

P1计算结果并将其保留在std::vector<std::vector<double>> data. 我希望这个data以尽可能快的方式从p1转移到p2std::vector<std::vector<double>> data

我用boost::archive::text_iarchive将其写入文本文件。由于它是跨平台兼容的,我可以在p2中使用boost::archive::text_oarchive读取它。但是它需要太多时间,因为它涉及磁盘读取和写入。所以我需要更好的方法来做这项工作。

请向我建议一些更快的跨平台数据传输方法。如果有人也能为我提供一些代码,我将不胜感激。

正如其他人已经提到的,最快和直接的方法是使用共享内存。下面是 Posix 系统的示例。

服务器创建一个共享内存对象,并通过将每个子向量写入长度加项来将向量序列化到内存中。

接收器打开共享内存对象,并将内存再次反序列化为矢量对象的向量。

寄件人:

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
#include <algorithm>
static const std::vector<std::vector<double>> vec = {
{ 1.0, 1.1, 1.2 },
{ 2.0, 2.1 },
{ 3.0, 3.1, 3.2, 3.3 },
};
int main(int argc, char *const argv[])
{
uint64_t vecsSize = 0;
for (const auto& v : vec) {
vecsSize += sizeof(double) * v.size() + sizeof(uint64_t);
}
// create a file of size 'vecsSize'
int fd = open("VEC", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
lseek(fd, vecsSize - 1, SEEK_SET);
write(fd, "", 1);
lseek(fd, 0, SEEK_SET);
// memory map the file into the process and copy the data into it
uint8_t* ptrFile = reinterpret_cast<uint8_t*>(mmap(0, vecsSize, PROT_WRITE, MAP_SHARED, fd, 0));
uint8_t* ptr = ptrFile;
for (const auto& v : vec)
{
reinterpret_cast<uint64_t*>(ptr)[0] = v.size();
ptr += sizeof(uint64_t);
std::copy(v.begin(), v.end(), reinterpret_cast<double*>(ptr));
ptr += sizeof(double) * v.size();
}
munmap(ptrFile, vecsSize);
close(fd);
return 0;
}

接收器:

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <algorithm>
template<class T>
inline std::ostream& operator<< (std::ostream& o, std::vector<T> const& v) {
for (auto const& i : v)
o << i << " ";
o << std::endl;
return o;
}
static std::vector<std::vector<double>> vec;
int main(int argc, char *const argv[])
{
int fd = open("VEC", O_RDONLY, S_IRUSR | S_IWUSR);
struct stat fileStat = { 0 };
fstat(fd, &fileStat);
uint64_t vecsSize = static_cast<uint64_t>(fileStat.st_size);
uint8_t* ptrFile = reinterpret_cast<uint8_t*>(mmap(0, vecsSize, PROT_READ, MAP_SHARED, fd, 0));
uint8_t* ptr = ptrFile;
while (ptr < ptrFile + vecsSize)
{
uint64_t vecSize = reinterpret_cast<uint64_t*>(ptr)[0];
ptr += sizeof(uint64_t);
std::vector<double> v(
reinterpret_cast<double*>(ptr),
reinterpret_cast<double*>(ptr) + vecSize);
ptr += sizeof(double) * vecSize;
vec.emplace_back(v);
}
munmap(ptrFile, vecsSize);
close(fd);
std::cout << vec;
return 0;
}

最新更新