c++ - 关于使用 freopen() 和 cin, cout 从文件中读取大输入的问题
问题描述
我想问一个关于 c++ i/o 的问题。如果我使用cin
, cout
with freopen()
,是否有必要放置sync_with_stdio(false)
或有什么方法可以加快速度?我注意到使用cout
withoutsync_with_stdio(false)
会快一点,并且不会比scanf()
.
阅读sync_with_stdio(false)
和cin
大约需要 3.7 秒 阅读没有sync_with_stdio(false)
大约需要 6 秒阅读scanf()
需要 1.7 秒
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
freopen("i.inp", "r", stdin);
freopen("o.out", "w", stdout);
vector<int> a(10000000, 0);
for (int i = 0; i < 10000000; i++) {
cin >> a[i];
//scanf("%d", &a[i]);
}
return 0;
}
写有sync_with_stdio(false)
和cout
需要 2.7 秒,没有sync_with_stdio(false)
需要 2.5 秒,同时printf
是最快的
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
freopen("i.inp", "r", stdin);
freopen("o.out", "w", stdout);
for (int i = 0; i < 10000000; i++) {
cout << 1 << " ";
//printf("%d", 1);
}
return 0;
}
阅读时,sync_with_stdio(false)
实际上有帮助,但用它写作需要更长的时间,这让我有点困惑,想知道我应该使用它还是坚持使用scanf
and printf
。
我使用代码块来测量执行时间。
解决方案
推荐阅读
- python - 命令控制台 AttributeError 模型中的 Django 错误
- python - 使用递归求函数的导数(三点端点公式)
- javascript - 如何溢出自动对焦最后一个元素
- javascript - 为 module.exports 定义参数
- kubernetes - Nginx Ingress“rewrite-target”注释不重写目标
- swift - 实例方法“items”要求“listen”符合“sequence”
- python - 用于存储和检索数据的 Python 队列线程安全
- async.js - export.run = async (client, message, args) => 做什么 Discord.js
- excel - MATLAB 单元格到字符串
- c - 如何计算包含一些未命名成员和零大小位域的位域结构的大小?