I am doing real-time rendering and trying to save the render_time
used per frame. So, it is continuous data until I close the viewport. In the rendering loop I am trying to do something like this:
std::ofstream f;
f.open("../data_file.dat");
//f << "render time" << '\n';
f << render_time << '\n';
f.close();
I want to save all the frame's render time, but instead of that, only the last value before closing the viewport is saved in the .dat
file.
// expected result
render time
0.02
0.06
0.01
...
// achieving result
0.01
I would appreciate it if someone suggests a solution that can add new values at the last row and keep previous values as well.
To always write to the end of a file, use std::ios::app
to open the file:
std::fstream file("path/to/file", std::ios::app);
A better solution would be to store the values in a buffer in memory and then write that to disk once your program finished running:
// Initialization
std::vector<double> renderTimes;
// ...
// On every frame
renderTimes.push_back(render_time);
// ...
// On shut down
std::fstream file("../data_file.dat");
if (!file) {
std::cerr << "Failed to open file\n";
return; // Skip the next section of code
}
// Store as human-readable text ...
for (double value: renderTimes) {
file << value << "\n";
}
// ... or in binary format
file.write(reinterpret_cast<char*>(renderTimes.data()), renderTimes.size() * sizeof(double));
This solution is superiour in most cases compared to writing directly to the file, because opening files has a considerable runtime overhead compared to simply writing a value to a location in memory. If your buffer grows too large to be easily kept in memory, you might have to write it to disk once in a while, but also that would not need to be done every frame.
Also worth mentioning as noted by @Jeremy Friesner is that this overhead is likely considerable enough to distort your measurements.