【C++】sync_with_stdio(false)
记录一下c++中std::ios::sync_with_stdio(false);的问题
C++中sync_with_stdio(false)是一种提升cin、cout效率的手段,使用C语言中的格式输入输出(scanf / prinrf)比C++中的标准输入输出(cin / cout)要快很多,在代码里加上std::ios::sync_with_stdio(false) 这个语句后,cin(cout)速度就会变得和scanf(printf)一样快
本质上是一个iostream与stdio流的同步的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流同步到了一起。cin和cout要与stdio同步,中间会有一个缓冲,所以导致cin,cout语句输入输出缓慢,这时就可以用这个语句,取消cin,cout与stdio的同步,说白了就是提速,效率基本与scanf和printf一致。
#include
#include
using namespace std;
int main()
{DWORD start_time = GetTickCount();{//此处为被测试代码/*sync_with_stdio(bool turnc);,其中 turnc 默认为 true*/std::ios::sync_with_stdio(false);for (int i = 0; i < 100000; i++){cout << i << endl;}}DWORD end_time = GetTickCount();cout << "The run time is:" << (end_time - start_time)*1.0 / 1000 << "s!" << endl;//输出运行时间system("pause");return 0;
}
但是用了sync_with_stdio(false)之后不能与printf和scanf同用,否则会出错,这就涉及到sync_with_stdio(false)的局限性。
printf( ) 用法:将变量的内容输出到显示器上
scanf( )用法:通过键盘将数据输入到变量中
iosream与stdio流的对应关系,C头文件对应 #include
| C stream | iostream |
| stdin | cin |
| wcin | |
| stdout | cout |
| wcout | |
| stderr | cerr |
| wcerr | |
| clog | |
| wclog |
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
同时在默认的情况下cin绑定的是cout,每次执行<<操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)来解除cin与cout的绑定,进一步加快执行效率。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
