0

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Rapture686
  • 411
  • 1
  • 4
  • 9
  • Yeah it's not an issue with raw transfer speed, it's the overhead involved with the way in which you're pushing it toward the disk. – rsethc Jul 18 '15 at 04:30
  • 2
    This code doesn't write 2-byte values, it outputs space-delimited text. – Blastfurnace Jul 18 '15 at 04:35
  • You're writing more like 10 * 480000000 ascii characters, plus spending all the time converting each one from int to string, and (depending on how good your compiler is!) maybe wasting time with stream formatting sentinels etc. for all those `<<`. – M.M Jul 18 '15 at 06:15

1 Answers1

3

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

Buddy
  • 10,874
  • 5
  • 41
  • 58
  • Beat me to it. Here's a good supporting reference: http://stackoverflow.com/questions/11563963/writing-a-binary-file-in-c-very-fast - his solution was more pure C, and probably unnecessary here. – mock_blatt Jul 18 '15 at 04:24
  • When I do this I get a compiler error under the first parameter of this. Saying it's a parameter of type char* and I'm using type short* Says it's incompatible – Rapture686 Jul 18 '15 at 04:26
  • @Rapture686 try `save.write((char*)world.worldGrid, sizeof(worldGrid));` – Buddy Jul 18 '15 at 04:27
  • @Buddy I'm an idiot haha. But if if one of my values in the array exceeds the value limit of the char type. Like an unsigned char limit is 255 right? What if one of my values it's let's say, 300 or something – Rapture686 Jul 18 '15 at 04:36
  • Basically the `write` method is saying "starting at this memory address, write this many bytes to the file"... what exactly is within that block of memory doesn't really matter -- it'll just get written to the file. To answer your question, a "short" is really "two bytes next to each other" – Buddy Jul 18 '15 at 04:39