【C++】C++中的sync_with_stdio(false)介绍

目录

一.sync_with_stdio(false)是什么

二.sync_with_stdio(false)怎么用


一.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一致。

二.sync_with_stdio(false)怎么用

#include<iostream>
#include<windows.h>
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 <stdio.h>

C streamiostream
stdincin
wcin
stdoutcout
wcout
stderrcerr
wcerr
clog
wclog
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);

同时在默认的情况下cin绑定的是cout,每次执行<<操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)来解除cincout的绑定,进一步加快执行效率。

  • 9
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟赵大宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值