简体   繁体   中英

C++ fstream writing to file very slow

I have a 2D world in my game consisting of tiles. Whenever I make a new world I initialize an array of 48 million tiles

short worldGrid[48000000];

I set the value for all 48 million, then I write those values into a file like this:

    std::fstream save("game_save", std::fstream::out);

    for (int x = 0; x < 48000000; x++)
    {

        save << world.worldGrid[x];
        save << " ";

    }
    save.close();

It's 48 million values, each one 2 bytes. So 96 million bytes, or 96 megabtyes. My problem is that this process inside the for loop alone takes 2 minutes to complete on my SSD. I don't feel like it should take 2 minutes and 5 seconds to write 96mb worth of data onto this file. If anyone has any advice I'd really appreciate it.

Try writing the array all at once, instead of 2 bytes-at-a-time.. Something like:

 save.write(world.worldGrid, sizeof(worldGrid));

See the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM