I have always heard that file input / output operations in C ++ are much slower than the C-style input / output. But I didn’t find any practical links regarding how slow they really are, so I decided to test it on my machine (Ubuntu 12.04, GCC 4.6.3, ext4 partition format).
First I wrote a ~ 900 MB file on disk.
C ++ ( ofstream ): 163s
ofstream file("test.txt"); for(register int i = 0; i < 100000000; i++) file << i << endl;
C ( fprintf ): 12s
FILE *fp = fopen("test.txt", "w"); for(register int i = 0; i < 100000000; i++) fprintf(fp, "%d\n", i);
I expected such a conclusion, it shows that writing to a file is much slower in C ++ C. Then I read the same file using C and C ++ I / O. Which made me exclaim that when reading from a file there is practically no difference in performance.
C ++ ( ifstream ): 12s
int n; ifstream file("test.txt"); for(register int i = 0; i < 100000000; i++) file >> n;
C ( fscanf ): 12s
FILE *fp = fopen("test.txt", "r"); for(register int i = 0; i < 100000000; i++) fscanf(fp, "%d", &n);
So, why does it take so long to record using a stream? Or, why is reading using the stream so fast compared to writing?
Conclusion: The culprit is std::endl , as answers and comments pointed out. Change the line file << i << endl; in file << i << '\n'; reduced the operating time to 16 s from 163 s.
c ++ c stream file-io
Rafi Kamal Jul 04 '13 at 10:35 2013-07-04 10:35
source share