As mentioned (and accepted) above, a drop endl
reduces the time by 50-60% (in my case, from 7 seconds to 2 seconds, more than 70%).
However, there is still room for improvement: formatting the overall stream. The following code further reduces execution time by another 75%, to 500 ms:
int a[100][100][50];
int main(int argc, char** argv)
{
char buff[64];
memset(a, 1, 100 * 100 * 50 * sizeof(int));
int count(0);
char delimiter = ',';
auto start = std::chrono::steady_clock::now();
std::ofstream ofs("test.csv", std::ofstream::out);
for (int r = 0; r < 100; r++)
{
for (int c = 0; c < 100; c++)
{
for (int s = 0; s < 50; s++)
{
sprintf_s(buff, "%d,%d,%d,%d\n", r, c, s, a[c][r][s]);
ofs << buff;
count++;
}
}
}
ofs.close();
auto end = std::chrono::steady_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << endl;
return count;
}
source
share