首页 > 解决方案 > 关于使用 freopen() 和 cin, cout 从文件中读取大输入的问题

问题描述

我想问一个关于 c++ i/o 的问题。如果我使用cin, coutwith freopen(),是否有必要放置sync_with_stdio(false)或有什么方法可以加快速度?我注意到使用coutwithoutsync_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)实际上有帮助,但用它写作需要更长的时间,这让我有点困惑,想知道我应该使用它还是坚持使用scanfand printf

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

标签: c++

解决方案


推荐阅读