Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is this C code faster than this C++ code ? getting biggest line in file
    primarykey
    data
    text
    <p>I have two versions of a program that does basically the same thing, getting the biggest length of a line in a file, I have a file with about 8 thousand lines, my code in C is a little bit more primitive (of course!) than the code I have in C++. The C programm takes about 2 seconds to run, while the program in C++ takes 10 seconds to run (same file I am testing with for both cases). But why? I was expecting it to take the same amount of time or a little bit more but not 8 seconds slower!</p> <p>my code in C:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #if _DEBUG #define DEBUG_PATH "../Debug/" #else #define DEBUG_PATH "" #endif const char FILE_NAME[] = DEBUG_PATH "data.noun"; int main() { int sPos = 0; int maxCount = 0; int cPos = 0; int ch; FILE *in_file; in_file = fopen(FILE_NAME, "r"); if (in_file == NULL) { printf("Cannot open %s\n", FILE_NAME); exit(8); } while (1) { ch = fgetc(in_file); if(ch == 0x0A || ch == EOF) // \n or \r or \r\n or end of file { if ((cPos - sPos) &gt; maxCount) maxCount = (cPos - sPos); if(ch == EOF) break; sPos = cPos; } else cPos++; } fclose(in_file); printf("Max line length: %i\n", maxCount); getch(); return (0); } </code></pre> <p>my code in C++:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdio.h&gt; #include &lt;string&gt; using namespace std; #ifdef _DEBUG #define FILE_PATH "../Debug/data.noun" #else #define FILE_PATH "data.noun" #endif int main() { string fileName = FILE_PATH; string s = ""; ifstream file; int size = 0; file.open(fileName.c_str()); if(!file) { printf("could not open file!"); return 0; } while(getline(file, s) ) size = (s.length() &gt; size) ? s.length() : size; file.close(); printf("biggest line in file: %i", size); getchar(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload