I have a C++ program where I do various experiments and during these experiments I output some values to a file using ofstream. The structure is basically:
Start timer
output to a file using ofstream (the output is, at most, a few words)
do some experimental work
Stop timer
My question, which is a bit broad, is can I ignore the time that the ofstream takes or it’s not something negligible ? or I guess it depends ?
First of all, from your pseudo code, you could just start the timer after the file output 🙂 But I’m guessing it’s not like that in the real app.
Beyond that, it’s obviously a matter of “it depends”. If you aren’t outputting all that much, and the code you’re interested in runs for minutes, then the output obviously won’t make much of a difference. If, on the other hand, you are trying to catch runtimes measured in microseconds, you’ll probably be mostly measuring the ofstream.
You could try doing various magics, like running the actual output on a thread, or just adding your messages to a previously allocated char array and outputting that at the end. However, everything incurs some runtime penalty; nothing is ever free.
Since you’re not interested in measuring the actual output time, you could compile a version without the output to do measurements, and a version with the output to debug the code. EDIT: or make that a runtime option. Nothing is ever free, but an “if (OutputEnabled)” is pretty close to “free” 🙂