I've written the following simple testing code, that creates 10 000 empty .txt files in a subdirectory.
#include <iostream>
#include <time.h>
#include <string>
#include <fstream>
void CreateFiles()
{
int i = 1;
while (i <= 10000) {
int filename = i;
std::string string_i = std::to_string(i);
std::string file_dir = ".\\results\\"+string_i+".txt";
std::ofstream outfile(file_dir);
i++;
}
}
int main()
{
clock_t tStart1 = clock();
CreateFiles();
printf("\nHow long it took to make files: %.2fs\n", (double)(clock() - tStart1)/CLOCKS_PER_SEC);
std::cin.get();
return 0;
}
Everything works fine. All 10 000 .txt files are created within ~3.55
seconds. (using my PC)
Question 1: Ignoring the conversion from int
to std::string
etc., is there anything that I could optimize here for the program to create the files faster? I specifically mean the std::ofstream outfile
usage - perhaps using something else would be relevantly faster?
Regardless, ~3,55
seconds is satisfying compared to the following:
I have modified the function so right now it would also fill the .txt files with some random i
integer data and some constant text:
void CreateFiles()
{
int i = 1;
while (i <= 10000) {
int filename = i;
std::string string_i = std::to_string(i);
std::string file_dir = ".\\results\\"+string_i+".txt";
std::ofstream outfile(file_dir);
// Here is the part where I am filling the .txt with some data
outfile << i << " some " << i << " constant " << i << " text " << i << " . . . "
<< i << " --more text-- " << i << " --even more-- " << i;
i++;
}
}
And now everything (creating the .txt files and filling it with short data) executes within... ~37
seconds. That's a huge difference. And that's only 10 000 files.
Question 2: Is there anything I can optimize here? Perhaps there exist some alternative that would fill the .txt files quicker. Or perhaps I have forgotten about something very obvious that slows down the entire process?
Or, perhaps I am exaggerating a little bit and ~37
seconds seems normal and optimized?
Thanks for sharing your insights!