gpt4 book ai didi

c++ - 交替的 cin/cout 很慢?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:11 24 4
gpt4 key购买 nike

开始,我正在做 std::ios_base::sync_with_stdio(false) .我有以下代码片段,从文本文件 (<input.txt >output.txt) 中读取一百万个整数:

int tests;
cin >> tests;
for (int i = 0; i < tests; ++i) {
int number;
cin >> number;
cout << number << "\n";
}

int tests;
cin >> tests;
vector<int> numbers(tests);
for (int i = 0; i < tests; ++i) {
cin >> numbers[i];
}
for (int i = 0; i < tests; ++i) {
cout << numbers[i] << "\n";
}

当然,实际上他们所做的不仅仅是打印相同的数字。问题是,第一个 block 花费了大约 4 倍的时间(6.2 秒对 1.8 秒)。

printf 重写相同的代码/scanf两种情况都需要 3 秒。这背后的原因是什么?

最佳答案

参见 std::basic_ios::tie ,特别是这些部分:

A tied stream is an output stream which is synchronized with the sequence controlled by the stream buffer (rdbuf()), that is, flush() is called on the tied stream before any input/output operation on *this.

By default, the standard streams cin, cerr and clog are tied to cout. Similarly, their wide counterparts wcin, wcerr and wclog are tied to wcout.

关键是要确保在典型的交互式程序中执行类似 cout << "Enter something: "; cin >> something; 的操作, 在程序等待输入之前,提示实际上出现在屏幕上。

但在你的情况下,那些额外的 flush()调用会破坏流可能做的任何缓冲,从而损害性能。

您可以使用 cin.tie(nullptr); 打破平局

关于c++ - 交替的 cin/cout 很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27253519/

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