gpt4 book ai didi

c++ - 关于使用 freopen() 和 cin、cout 从文件读取大量输入的问题

转载 作者:行者123 更新时间:2023-12-05 06:56:45 32 4
gpt4 key购买 nike

我想问一个关于c++ i/o的问题。如果我将 cincoutfreopen() 一起使用,是否需要放置 sync_with_stdio(false) 还是有什么办法可以加快速度吗?我注意到在不使用 sync_with_stdio(false) 的情况下使用 cout 会快一点,而且不比 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) 实际上有帮助,但用它编写需要更长的时间,这让我有点困惑,想知道我是否应该使用它,还是坚持使用 scanfprintf

我使用代码块来测量执行时间。

最佳答案

我不确定这种情况,但也许你还想尝试输入这两行:

  1. cin.tie(0); -> 使 cin 更快
  2. cout.tie(0); -> 使 cout 更快然后检查性能。

关于c++ - 关于使用 freopen() 和 cin、cout 从文件读取大量输入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65068411/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com