我只知道使用cin和cout会比scanf和printf慢。但是,the top answer表示使用std :: ios :: sync_with_stdio(false)可能比scanf& printf更快。但是,我做了这个实验,发现它不对。这是我的错吗?为什么?
使用cin& cout比使用scanf& printf(包括读取文件)更快的正确代码是什么。感谢。
这是我的代码:
生成数据
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
FILE *data = freopen("test.in","w",stdin);
//FILE *fi = freopen("test.in","r",stdin);
//FILE *fo = freopen("test.out","w",stdout);
int main()
{
for(int i=1;i<10000000;i++)
printf("%d\n",i);
return 0;
}
使用scanf&amp; printf
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
int ans = 1;
while(~scanf("%d",&ans))
{
printf("%d\n",ans);
}
return 0;
}
使用cin&amp; cout(std :: ios :: sync_with_stdio(true))
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
std::ios::sync_with_stdio(true);
int ans = 1;
while(std::cin>>ans)
{
std::cout<<ans<<std::endl;
}
return 0;
}
使用std :: ios :: sync_with_stdio(false)
#include<cstdio>
#include<iostream>
#include<ctime>
#include<fstream>
#include<iomanip>
//FILE *data = freopen("test.in","w",stdin);
FILE *fi = freopen("test.in","r",stdin);
FILE *fo = freopen("test.out","w",stdout);
int main()
{
std::ios::sync_with_stdio(false);
int ans = 1;
while(std::cin>>ans)
{
std::cout<<ans<<std::endl;
}
return 0;
}
结果:
scanf version: 4.918 seconds
iostream version: 51.266 seconds
iostream with sync_with_stdio(false): 31.815 seconds
答案 0 :(得分:6)
您每次使用std::cout
时都会std::endl
。
不要那样做。相反,如果您想匹配'\n'
版本的行为,只需输出printf
:
std::cout << ans << '\n';