Cover Image for Fast input and output in C++
64 views

Fast input and output in C++

In competitive programming or other situations where input and output performance is critical, you can use techniques to achieve fast input and output in C++. The standard input/output streams (cin and cout) are convenient but may not be the fastest for large input or output. Here are some techniques to optimize input and output speed:

  1. Use std::ios::sync_with_stdio(false): By default, cin and cout are synchronized with the C standard I/O functions, which can be slower than direct input/output. You can disable synchronization for a potential speed boost:
   std::ios::sync_with_stdio(false);

Note that this should be called before any input/output operation.

  1. Use cin.tie(nullptr): By default, cin is tied to cout, meaning that cout is flushed before reading from cin. You can untie them for better performance:
   std::cin.tie(nullptr);
  1. Use '\n' instead of endl: Avoid using endl when printing to cout because it flushes the output buffer. Instead, use '\n' for line breaks:
   std::cout << "Hello, World!\n";
  1. Use a custom input function: For reading large amounts of input data, using cin for each input operation can be slow. You can create a custom input function that reads data more efficiently. For example:
   int readInt() {
       int x;
       std::cin >> x;
       return x;
   }

This function reads an integer using cin and can be faster than direct cin usage in certain situations.

  1. Use printf and scanf for formatted output/input: If you prefer to use C-style I/O for better performance, you can use printf and scanf for formatted output and input, respectively.
   printf("Hello, World!\n");
   int x;
   scanf("%d", &x);
  1. Buffered Output: If you are performing a large number of output operations, consider using a custom output buffer to reduce the overhead of multiple cout calls.

Here’s an example of combining these techniques:

#include <iostream>
#include <cstdio>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    // Faster input using scanf
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        int x;
        scanf("%d", &x);
        // Process x
    }

    // Faster output using printf
    printf("Output: %d\n", 42);

    return 0;
}

Keep in mind that the choice of optimization techniques depends on the specific requirements of your program and the input/output sizes. In most situations, the default I/O streams (cin and cout) are sufficient and easy to use, but for time-critical applications, these optimizations can make a noticeable difference in performance.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS