C++, printf vs cout performance
C++, printf vs cout performance
我在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 更快?
查看此答案以更清晰。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- std::cout输出int时出现编译错误
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- C++ Setter/Getter,cout 工作,printf 失败
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 结构元素名称要 cout?
- 使用模板类重载 cout
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- 带有 cout 的指针在C++
- cout 指针时的实际数字
- COUT 无法提供输出可能是由于内联组装
- C++程序在一定行后未正确编译[cout语句]
- C++, printf vs cout performance