By default the reading with cin
is desperately slow compared to its counterpart scanf
... when logic tells us that it should not be like this:
- With
cin
a direct call is made to the function that knows what the type of the destination variable is. - With
scanf
the function must read the format string (with the dozens of possibilities that exist) to know how to interpret the entry and then process it.
However with a simple example it is easy to see that the reality is different:
#include <iostream>
#include <chrono>
#include <string>
void cinFunc()
{
int N;
for( int i=0; i<100000; i++)
std::cin >> N;
}
void scanfFunc()
{
int N;
for( int i=0; i<100000; i++)
scanf(" %d",&N);
}
template<typename Func>
void Test(std::string const& title, Func f)
{
auto start = std::chrono::steady_clock::now();
f();
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
std::cout << "Test " << title << ":\t" << std::chrono::duration<double, std::milli>(diff).count() << " ms\n";
}
int main()
{
Test("cin",cinFunc);
Test("scanf",scanfFunc);
return EXIT_SUCCESS;
}
The program runs with a file containing 200,000 1-digit integers separated by a space and the results speak for themselves:
Test cin: 64.7967 ms
Test scanf: 49.855 ms
What is the reason that the reading of C ++ itself is so slow? How can this situation be corrected?