1

Actually, I came across a competitive question where I need to input into a large array, but I am getting TLE error so is there is any other way than the traditional ways to reduce the TLE.

I have tried some of the tips but it doesn't work.

#include<bits/stdc++.h> //rather than other files
ios_base :: sync_with_stdio(false);
cin.tie(NULL)

the time decreases but not so much.

So is there is any other method than these to reduce the input time of inputting integers to an array?

JeJo
  • 20,530
  • 5
  • 29
  • 68
Shiva Chandel
  • 101
  • 2
  • 11
  • **Recommended reading:** [Why should I not #include ?](https://stackoverflow.com/q/31816095/560648) – Lightness Races in Orbit Jul 19 '19 at 13:39
  • Related: https://stackoverflow.com/questions/14208472/input-faster-than-scanf-for-int-in-c-c – posilon Jul 19 '19 at 13:59
  • For something even faster, you can use read() to bring your input data from the file/stdin to memory in big chunks, and then parse each chunk. This will be faster than accessing the file/stdin a much greater number of times and reading a much smaller number of characters each time. – posilon Jul 19 '19 at 14:07
  • 1
    You have two primary issues: Input speed and conversion speed. The input speed is the speed you can obtain the data. The conversion speed is converting the integers from text representation to internal representation. If you want fast input, see the `istream::read()` method. The bottleneck is waiting for the newline; otherwise you could perform a block or bulk read. – Thomas Matthews Jul 19 '19 at 14:07
  • Most performance issues with online judges (or contests), is the algorithm. Timeouts are due to choosing slow algorithms. Most problems or issues rarely involve optimization techniques (such as loop unrolling). – Thomas Matthews Jul 19 '19 at 14:11

2 Answers2

2

scanf() is faster than cin for input. The sync_with_stdio(false) and cin.tie(NULL) lines are only recommended if you are unable to use scanf() and printf().

For even faster methods for inputting integers you may try this source: https://www.hackerearth.com/practice/notes/fast-io-optimization-in-c/

  • Out of interest, the link you provided uses the `register` keyword, which is deprecated in C++17 - should one replace the keyword by something, or can one simply omit it if he works with C++17 with this being somehow automatically optimized? – Aziuth Jul 19 '19 at 13:29
0

You should increase you input buffer. That will drastically improve your performance for large data:

constexpr size_t BufferSize = 65536;
char buffer[BufferSize ];
std::ifstream file{};
file.rdbuf()->pubsetbuf(buffer, BufferSize );

fread with a big buffer will also be faster. Please try.

Armin Montigny
  • 7,879
  • 3
  • 11
  • 29