0

I have a C++ program to write stuffs to a file, but the write speed is extremely low.
Here's it:

#include <string>
#include <fstream>
#include <limits.h>
#include <iostream>

int main()
{
    std::ofstream file("Important.txt");

    for (int i = 0; i < INT_MAX; i++)
    {
        file << 0;
    }
    file.close();
    return 0x45;
}

The write speed barely reaches 5.6 mbps (as task manager shows).

Then I tried with win32 api, but the write speed barely reached 0.5 mpbs (also according to taskmanager)

I have seen programs write speeds upto 130 mbps on my drive. I also tried Crystal Disk Mark 8 to check my write speeds and it shows around 135 mbps. Any suggestions on how to increase disk write speed.

I don't think this is a duplicate of This. I just want to write simple strings and int to the file

Someone
  • 126
  • 8
  • What do you want to achieve? Write more bytes in one loop would be faster. – Louis Go Oct 05 '21 at 04:04
  • Or write things in parallel. – Zois Tasoulas Oct 05 '21 at 04:06
  • You could try using a `std::ostringstream` for the formatting 1st, and write all the formatted text in the file in one go. – πάντα ῥεῖ Oct 05 '21 at 04:07
  • 3
    The answer is always to use a bigger buffer. – user207421 Oct 05 '21 at 04:09
  • `return 0x45;` it not the thing you'd normally like to do in main – phuclv Oct 05 '21 at 04:36
  • 2
    @user207421 Not always, it is about using buffers smartly :) I've used boost::asio and a few DMA block sized buffers to write as much as 10Gb/s to a raid array using C++. So it can be done. Basically tell the controller next buffer is at that address, and while writing the next buffer the first buffer is written by the DMA controller – Pepijn Kramer Oct 05 '21 at 04:37
  • 2
    @zois Have you ever tried to speed writing by concurrency? This can result in the opposite because you may get multiple threads competing for the same resource (the drive to write to). – Scheff's Cat Oct 05 '21 at 04:38
  • @Scheff'sCat I was about to say that. Or you would need to know up front the full buffer size and which piece of data is going to end up where in your buffer and communicate that to the threads up front. (which avoids the needs for locks). For very structured data this can be done, not for variable length strings – Pepijn Kramer Oct 05 '21 at 04:40

0 Answers0