Fastest way to write large STL vector to file using STL

后端 未结 7 721
一个人的身影
一个人的身影 2021-02-06 06:53

I have a large vector (10^9 elements) of chars, and I was wondering what is the fastest way to write such vector to a file. So far I\'ve been using next code:

ve         


        
7条回答
  •  梦谈多话
    2021-02-06 07:14

    OK, I did write method implementation with for loop that writes 256KB blocks (as Rob suggested) of data at each iteration and result is 16 seconds, so problem solved. This is my humble implementation so feel free to comment:

     void writeCubeToFile(const vector &vs)
     {
         const unsigned int blocksize = 262144;
         unsigned long blocks = distance(vs.begin(), vs.end()) / blocksize;
    
         ofstream outfile("nanocube.txt", ios::out | ios::binary);
    
         for(unsigned long i = 0; i <= blocks; i++)
         {
             unsigned long position = blocksize * i;
    
             if(blocksize > distance(vs.begin() + position, vs.end())) outfile.write(&*(vs.begin() + position), distance(vs.begin() + position, vs.end()));
             else outfile.write(&*(vs.begin() + position), blocksize);
         }
    
         outfile.write("\0", 1);
    
         outfile.close();
    }
    

    Thnx to all of you.

提交回复
热议问题