C++, printf vs cout performance

C++, printf vs cout performance

本文关键字:cout performance vs printf C++      更新时间:2023-10-16

我在C++中编写了以下程序来测量以不同方式打印到默认输出流所需的时间:

#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main() {
// Get starting timepoint
auto start = high_resolution_clock::now();
for (int i=0;i<100000;i++)
{
cout << "Hello";
}
// Get ending timepoint
auto stop = high_resolution_clock::now();
// Get duration. Substart timepoints to
// get durarion. To cast it to proper unit
// use duration cast method
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: "
<< duration.count() << " microseconds" << endl;
return 0;

}

在第一轮,我用:cout << "Hello" << endl;运行它,花了 147,570 微秒。

在第二轮中,我用:cout << "Hellon";,花了128,543微秒。

最后,我用:printf("Hellon");运行它,花了 121,223 微秒。

是什么导致了这种明显的差异?

注意:我从每个测试的 10 个测试中取平均值。

默认情况下,cin/cout会浪费时间将自身与 C 库的 stdio 缓冲区同步,以便您可以自由地将对 scanf/printf 的调用与 cin/cout 上的操作混合在一起。

关闭此功能

std::ios_base::sync_with_stdio(false);

此外,许多C++教程告诉您编写 cout <<endl 而不是 cout <<''。但 endl 实际上更慢,因为它强制刷新,这通常是不必要的。(例如,如果您正在编写交互式进度条,则需要刷新,但在写入一百万行数据时则不需要刷新。写""而不是 endl。

此外,由于C++是面向对象的,cin 和 cout 是对象,因此由于对象绑定,总体时间会增加

因此,一个简单的行,">std::ios_base::sync_with_stdio(false(;"可以使cin/cout比printf/scanf更快。 希望这对你有帮助

OOP 中的任何内容都将比纯函数式语言(如 C(中的等效语言慢。 在这种情况下,内部同步/刷新通常会减慢 iostream I/O 的速度,Furthur,实际时间也因编译器而异。

在C++程序中使用 scanf(( 比使用 cin 更快?

查看此答案以更清晰。