char *自定义类型

时间:2018-11-20 13:18:58

标签: c++ io

我有一个自定义类型。假设它是具有强度的3D点类型,因此看起来像这样:

struct Point{
public:
    double x,y,z;
    double intensity;
    //Imagine a constructor or everything we need for such a class here
};

和另一个使用该点向量的类。

class Whatever{
//...
public:
    std::vector<Point> myPts;
//...
};

我希望能够从文件创建此向量。这意味着我有一个像这样的文件:

X1 Y1 Z1 I1 
X2 Y2 Z2 I2
X3 Y3 Z3 I3 
....
Xn Yn Zn In

我想找到一种快速的技术来分离每条线,并为每条线建立一个点,并建立我的向量。由于这是我必须要做的很多事情,所以我正在寻找最快的方法。

基本解决方案是逐行读取文件,转换为stringstream并从此stringstream创建:

while(std::getline(file, line)){
    std::istringstream iss(line);
    Point pt;
    iss >> pt.x >>  pt.y >> pt.z >> pt.intensity;
    vector.add(pt);
}

但是这太浪费时间了。因此,第二种方法是在缓冲区中读取文件(整个文件或文件的一部分),并格式化缓冲区以从中创建矢量。使用内存映射文件,我可以快速读取缓冲区,但是如何格式化缓冲区以创建我的点而不使用我认为很慢的stringstream?

编辑: 我使用了以下代码:

std::clock_t begin = clock();
    std::clock_t loadIntoFile, loadInVec;
    std::ifstream file(filename);
    if (file) {
        std::stringstream buffer;
        buffer << file.rdbuf();
        file.close();
        loadIntoFile = clock();
        while (!buffer.eof()) {
            Point pt = Point();
            buffer >> pt.x >> pt.y >> pt.z >> pt.intens >> pt.r >> pt.g >> pt.b;
            pts.push_back(pt);
        }
        loadInVec = clock();
    }
    std::cout << "file size" << pts.size() << std::endl;
    std::cout << "load into file : " << (loadIntoFile - begin) / (double)CLOCKS_PER_SEC << std::endl;
    std::cout << "load into vec : " << (loadInVec - loadIntoFile) / (double)CLOCKS_PER_SEC << std::endl;

结果是:

file size : 7756849
load into file : 2.619
load into vec : 31.532

EDIT2: 删除stringstream缓冲区后,我的时间为34.604s 并且将push_back更改了emplace_back 34.023秒

0 个答案:

没有答案