cin与scanf的读入速度比较(1e7与1e6的速度规模测试)

前言

在做一些读入数据规模非常大的题目时,可能会遇到由于使用cin而导致TLE的问题。在这里我们就简单对比一下cinscanf在速度上到底是由什么样的差别。
其实这个问题也有不少人写,但是感觉测试的不算全面。

配置

I5-8250U + 8G + Intel辣鸡SSD
普通的轻薄本配置。

先说结论

使用Dev-C++以下时间已取平均值。

  • 1e7的数据规模
    1. scanf读入需要时间:1.1s左右
    2. cin读入需要时间:7.0s左右
    3. std::ios::sync_with_stdio(false); 禁用同步:1.5s左右
  • 1e6的数据规模
    1. scanf读入需要时间:0.12s左右
    2. cin读入需要时间:0.7s左右
    3. std::ios::sync_with_stdio(false); 禁用同步:0.16s左右

我的疑惑…

文末会附上代码,大家可以自己跑跑试试。
在Dev-C++中比VS2017要慢,这个没什么问题。
但是在VS2017中,cin真的很快…不管是启用同步还是禁用同步,cin都可以在1e7的读入上只花1.2s左右,而且scanf在包含iostream的情况下很慢…
而且在Dev-C++中,同时包含iostream和stdio或者只包含iostream都会让scanf的速度很慢。
上边的问题我真的不知道为什么,希望有明白的朋友在评论区讨论一下,谢谢。

代码

生成随机数据:

#include 
#include 
using namespace std;

#define MAX 1e7

int main()
{
	ofstream out("data.txt");
	for(int i = 0; i < MAX; i++)
		out << rand() << ' ';
		
	return 0;
}

读取速度测试(请按照需要自行修改):

#include 
//#include 
#include 

const int MAXN = 1e6;

int numbers[MAXN];

int main()
{
	freopen("data.txt", "r", stdin);
	//std::ios::sync_with_stdio(false);
	
	int end;
    int start = clock();
	
	//scanf
	for (int i = 0; i < MAXN; i++)
		scanf("%d", &numbers[i]);

	//cin
//	for (int i = 0; i < MAXN; i++)
//		std::cin >> numbers[i];
    
    end = clock();
    printf("%.2lfs\n", double(end - start) / CLOCKS_PER_SEC);

	return 0;
}

参考

探寻C++最快的读取文件的方案

你可能感兴趣的:(cin与scanf的读入速度比较(1e7与1e6的速度规模测试))