读入外挂 std::ios::sync_with_stdio(false);
2017-08-09 11:13
363 查看
在此郑重说明,这是水的一篇博客,哈哈哈哈哈。
当然上面的也可以换成
可以将cin和scanf的效率相匹敌。
详情说明:
scanf在Linux平台上测试结果为2.01秒
cinLinux平台上测试结果为6.38秒
cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句
取消同步后效率究竟如何?经测试运行时间锐减到了2.05秒,与scanf效率相差无几了!有了这个以后可以放心使用cin和cout了。
读入外挂
当遇到坑的题scanf都过不了的时候就用这个,不过这样的情况一般都是代码效率问题。#include <bits/stdc++.h> using namespace std; inline int Scan() //inline为内联函数,目的是预处理,可减少时间 { int res = 0, ch, flag = 0; if((ch = getchar()) == '-') //判断正负 flag = 1; else if(ch >= '0' && ch <= '9') //得到完整的数 res = ch - '0'; while((ch = getchar()) >= '0' && ch <= '9' ) res = res * 10 + ch - '0'; return flag ? -res : res; } int main() { int n=Scan(); printf("%d\n",n); }
当然上面的也可以换成
long long类型的
cin的小技巧
ios::sync_with_stdio(false);
可以将cin和scanf的效率相匹敌。
详情说明:
scanf在Linux平台上测试结果为2.01秒
const int MAXN = 10000000; int numbers[MAXN]; void scanf_read() { freopen("data.txt","r",stdin); for (int i=0;i<MAXN;i++) scanf("%d",&numbers[i]);
cinLinux平台上测试结果为6.38秒
const int MAXN = 10000000; int numbers[MAXN]; void cin_read() { freopen("data.txt","r",stdin); for (int i=0;i<MAXN;i++) std::cin >> numbers[i]; }
cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句
std::ios::sync_with_stdio(false);,这样就可以取消cin于stdin的同步了。
const int MAXN = 10000000; int numbers[MAXN]; void cin_read_nosync() { freopen("data.txt","r",stdin); std::ios::sync_with_stdio(false); for (int i=0;i<MAXN;i++) std::cin >> numbers[i]; }
取消同步后效率究竟如何?经测试运行时间锐减到了2.05秒,与scanf效率相差无几了!有了这个以后可以放心使用cin和cout了。
相关文章推荐
- std::ios::sync_with_stdio(false);
- 杭电ACM 找循环节 std::ios::sync_with_stdio(false);
- ios::sync_with_stdio(false);(读入优化)
- YT14-HDU-找循环节 (关于std::ios::sync_with_stdio(false);的作用和疑问)
- C++ 里利用 std::ios::sync_with_stdio(false) 解决TLE问题
- 关于std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false);--------探寻C++最快的读取文件的方案
- std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false);
- std::ios::sync_with_stdio(false); cin.tie(0);
- 探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false) (转)
- 转载——探寻C++最快的读取文件的方案std::ios::sync_with_stdio(false)——转载
- std:ios::sync_with_stdio(false);
- cin/cou效率太慢?试一下 ios::sync_with_stdio(false);
- 关闭同步流(ios::sync_with_stdio(false);)
- ios::sync_with_stdio(false);
- ios::sync_with_stdio(false) 改变C++流输入输出的速度
- std::ios_base::sync_with_stdio()
- ios::sync_with_stdio(false) 改变C++流输入输出的速度
- ios::sync_with_stdio(false) 改变C++流输入输出的速度