I am coding for various programming olympiads and am trying to improve time efficiency. I’m looking for the fastest way to get input, using the gcc compiler without any external library.
I’ve previously used cin and cout, but found that scanf and printf are much faster. Is there an even faster way? I don’t care of space complexity that much, I rather prefer better time.
That streams are always slower than the C-API functions is a pretty common misconception because by default, they synchronize with the C-layer. So yeah, that’s a feature, not a bug.
Without sacrificing type safety (and readability, depending on your taste), you possibly gain performance with streams by using:
A little indicator:
With g++ -O3, and a big text file:
How this applies to your case depends. Modify this toy-benchmark, add more tests, and compare e.g. something like
std::cin >> a >> b >> cwithscanf ("%d %d %d", &a, &b, &c);. I guarantee, with optimizations (i.e. without being in debug mode), performance differences will be subtle.If that does not saturate your needs, you might try other approaches, e.g. reading the whole file first (may or may not bring more performance) or memory maps (which is a non-portable solution, but the big desktops have them).
Update
Formatted input: scanf vs. streams
Results: