Why std::cin has such a low efficiency when processing float points on Codeforces?

Revision en2, by xyf007, 2021-10-09 18:13:30

In Bubble Cup 14, I used std::cin on problem G. Shortest Path and got TLE. See my submission 131334076. Note that I used std::ios_base::sync_with_stdio(false) and std::cin.tie(nullptr) to accelerate it, but it still got TLE. However, I simply changed it to std::scanf and got AC, with an execution time of 342ms. See my submission 131336297.

I tested the efficiency on my computer, but it only took me around 200ms to read $$$10^6$$$ double variables. My computer is Intel i7 8565U. My compiler is gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04) with -O2. I will show my code and generator below.

My Code:

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
template <typename T>
void checkmax(T &x, T y) {
  if (x < y) x = y;
}
template <typename T>
void checkmin(T &x, T y) {
  if (x > y) x = y;
}
int n;
double a[1000001];
int main(int argc, char const *argv[]) {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr), std::cout.tie(nullptr);
  std::cin >> n;
  for (int i = 1; i <= n; i++) std::cin >> a[i];
  // std::scanf("%d", &n);
  // for (int i = 1; i <= n; i++) std::scanf("%lf", &a[i]);
  return 0;
}

My generator:

#include <bits/stdc++.h>
std::mt19937 rng(
    std::chrono::_V2::steady_clock::now().time_since_epoch().count());
template <typename T>
T Rand(T l, T r) {
  return std::uniform_real_distribution<T>(l, r)(rng);
}
int n = 1000000;
int main(int argc, char const *argv[]) {
  std::ofstream fout("data.in");
  fout.precision(6);
  fout << n << '\n';
  fout << std::fixed;
  for (int i = 1; i <= n; i++) fout << Rand(-1e6, 1e6) << " \n"[i == n];
  return 0;
}

Can anyone explain it?

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English xyf007 2021-10-09 18:13:30 71 (published)
en1 English xyf007 2021-10-09 18:02:03 1996 Initial revision (saved to drafts)