I will show you C # and C ++ code that perform the same task: to read the same text file, separated by the "|" and save with the text delimited by "#".
When I execute the program in C ++, the elapsed time is 169 seconds.
UPDATE 1: Thanks to Seth (compilation with: cl / EHsc / Ox / Ob2 / Oi) and GWW for changing the position of line s outside the loops, elapsed time has been reduced to 53 seconds. I also updated the code.
UPDATE 2: Do you have any suggestions for improving C ++ code?
When I run the C # program, the elapsed time is 34 seconds!
The question is, how can I increase the speed of C ++ compared to C # one?
C ++ program:
int main () { Timer t; cout << t.ShowStart() << endl; ifstream input("in.txt"); ofstream output("out.txt", ios::out); char const row_delim = '\n'; char const field_delim = '|'; string s1, s2; while (input) { if (!getline( input, s1, row_delim )) break; istringstream iss(s1); while (iss) { if (!getline(iss, s2, field_delim )) break; output << s2 << "#"; } output << "\n"; } t.Stop(); cout << t.ShowEnd() << endl; cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl; return 0; }
C # program:
static void Main(string[] args) { long i; Stopwatch sw = new Stopwatch(); Console.WriteLine(DateTime.Now); sw.Start(); StreamReader sr = new StreamReader("in.txt", Encoding.Default); StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default); object[] cols = new object[0];
UPDATE 3:
Well, I have to say that I am very happy for the help received and because the answer to my question is satisfied.
I slightly altered the text of the question, and I tested the solutions, which were kindly raised by Molbdlino and Bo Persson.
Saving Seth readings for the compilation command (i.e. cl / EHsc / Ox / Ob2 / Oi pgm.cpp):
Bo Persson's solution took an average of 18 seconds to complete, really good, considering the code is close to what I like).
Molbdlino's solution took 6 seconds on average, really awesome !! (also thanks to Konstantin).
It is never too late to learn, and I have learned valuable things with my question.
Best wishes.