我有两个进程p1和p2。p1在x86中构建,p2使用x64平台构建(Visual 2013/MFC/C++)
p1计算结果并将其保存在std::vector<std::vector<double>> data
中。我希望这个data
以最快的速度从p1转到p2's std::vector<std::vector<double>> data
。
我使用boost::archive::text_iarchive
将其写入文本文件。由于它是跨平台兼容的,所以我可以使用boost::archive::text_oarchive
在p2中阅读它。但这需要太多的时间,因为它涉及磁盘读取和写入。所以我需要更好的方法来做这份工作。
请建议我一些更快的方式进行跨平台的数据传输。如果有人也能给我一些代码,我会非常感激的。
发布于 2018-08-11 14:32:27
正如其他人已经提到的,最快和直接的方式是使用共享内存。下面是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;
}
https://stackoverflow.com/questions/51799094
复制相似问题