Can someone please explain to me when using C FILE I/O is faster than using the C++ <fstream> library? Because it's a real headache trying both on every code and testing them with difficult test cases, and measuring the time taken with <time.h> ! thanks:)
C++ fstream in nothing but a wrapper for C FILE I/O! And here's why it's slow:
Fstream has a memeber of type "filebuf", filebuf has a memeber of type "__basic_file<char>", and __basic_file has a member of type FILE*, and the result of all this indirectness is the slowness, while C FILE I/O operates directly through FILE*s.
i see what you mean, but in practice using C FILE I/O isn't always faster! although that sometimes it's a lot faster, sometimes it turns out to be a little slower(really no joke). Do you suggest i always use C FILE I/O, although i am writing code in C++?
No, I don't suggest using anything from C that has an equaly (or more) functional alternative which is pure C++! Some people ALWAYS use scanf, printf and that kind of stuff, but I never do! If you don't use the file streams more than a million times, the time difference is irrelevant, and I suggest using C++ file streams! Only, and only if you use the file I/O absurdely many times, then use C FILE I/O, for speed.
I doubt there's any noticable performance difference between fstream and cstdio. File I/O is bottlenecked more by the actual I/O to disk than the API used.
I just made a test with 100 000 I/O operations, and the C FILE I/O is 3 times faster! But, it's irreleveant, unless you are doing it a lot!
Heres the test I made:
If you need performance, you use memory mapped I/O or async I/O, madvise, fadvise, mincore, etc. system calls. None of this is supported by C++ iostream, so there is really *no* choice here. Funny, I can use these advanced streaming options in Java, but not in C++ :D
If you need performance, you use memory mapped I/O or async I/O, madvise, fadvise, mincore, etc. system calls. None of this is supported by C++ iostream, so there is really *no* choice here. Funny, I can use these advanced streaming options in Java, but not in C++ :D
What do you mean ? You can use memory mapped files in every programming language, it is a feature supported by operating system itself.
you mean that doing cout<<'\n'; instead of cout<<endl; makes your program faster?
Maybe a few microseconds faster, yes... but it also means you are not flushing the buffer.
Really, unless you understand what flushing the buffer actually means, I would not worry about this, and would continue to use endl. Don't bother going back and switching all your endl's to \n's just because it's "faster". The potential issues caused by failing to flush the buffer might prove to be more of an issue than your program running 4 microseconds slower.
The speed difference is not worth getting your panties in a twist over unless you're doing it several thousand times like viliml was.