关于两种文件 IO 的效率对比

· · 闲话

关于 IO: 本人测试了 freopen + scanf/printf 的文件 IO 和 ifstream/ofstream + 关闭同步流和 tie 的文件 IO 的效率。

以下是测试用机信息:

以下是测试用代码: 1.cpp:

#include <bits/stdc++.h>
using namespace std;

int n;
long long sum;

signed main() {
    auto st = chrono::high_resolution_clock().now();

    freopen("in.in", "r", stdin);
    freopen("a.out", "w", stdout);

    scanf("%d", &n);
    for (int i = 1, x; i <= n; ++i)
        scanf("%d", &x), sum += x;
    printf("%lld\n", sum);

    auto ed = chrono::high_resolution_clock().now();
    auto tim = chrono::duration_cast<chrono::microseconds>(ed - st).count();
    cerr << tim << "us\n";

    return 0;
}

2.cpp:

#include <bits/stdc++.h>
using namespace std;

int n;
long long sum;

signed main() {
    auto st = chrono::high_resolution_clock().now();

    ifstream fin("in.in");
    ofstream fout("b.out");

    ios::sync_with_stdio(0), fin.tie(0), fout.tie(0);

    fin >> n;
    for (int i = 1, x; i <= n; ++i)
        fin >> x, sum += x;
    fout << sum << '\n';

    auto ed = chrono::high_resolution_clock().now();
    auto tim = chrono::duration_cast<chrono::microseconds>(ed - st).count();
    cerr << tim << "us\n";

    return 0;
}

gen.py:

import random
n = int(1e5)
print(n)
for i in range(1, n + 1):
    print(random.randint(1, int(1e9)))

以下单位为 \mu s: 在 Windows 下随机 10 组数据得到结果如下: | 文件 IO 方式 | Testcase 1 | Testcase 2 | Testcase 3 | Testcase 4 | Testcase 5 | |---|---|---|---|---|---| |freopen| 35569 | 36555 | 38725 | 34319 | 34990 | |fstream| 191 | 176 | 180 | 180 | 184 |

文件 IO 方式 Testcase 6 Testcase 7 Testcase 8 Testcase 9 Testcase 10
freopen 33606 36805 34020 34193 34692
fstream 174 181 172 173 175

在 NOI Linux 虚拟机下随机 10 组数据得到结果如下: | 文件 IO 方式 | Testcase 1 | Testcase 2 | Testcase 3 | Testcase 4 | Testcase 5 | |---|---|---|---|---|---| |freopen| 27168 | 25310 | 19873 | 33184 | 18697 | |fstream| 25571 | 31266 | 19679 | 37755 | 19522 |

文件 IO 方式 Testcase 6 Testcase 7 Testcase 8 Testcase 9 Testcase 10
freopen 32555 35865 10404 44809 37931
fstream 35281 37484 13635 45106 40398

两个环境下的两种文件 IO 方式各自取算术平均数得到:

|| Windows | NOI Linux | |---|---|---| |freopen| 35347.4 | 28579.6 | |fstream| 178.6 | 30569.7 |

(数据统计和平均数计算都是本人一个一个字打的,可能有误差,请见谅!)

在 Windows GCC 14.0.2 上 fstream 将 freopen 吊着打,而在 NOI Linux GCC 9.3.0 上 freopen 具有微弱优势。个人猜测可能是因为较新版本的编译器对 C++ 特有内容的优化更加激进,而对于继承自 C 的内容考虑兼容性无法做到更好的优化。另外,NOI Linux 下 freopen 的测试结果相对更优,或许也反映了 Linux 系统本身在读写上的优化更优秀。

本人时间精力有限,无法测试 Windows 低版本 GCC 和 NOI Linux 高版本 GCC 的情况及 clang 的情况。以上内容仅供娱乐,感兴趣可以在自己电脑上测一下。