[英]C++, printf vs cout performance
我在C++写了下面的程序,用不同的方式测量打印到默认的output stream需要多少时间:
#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 << "Hello\n";
并花费了 128,543 微秒。
最后,我运行它: printf("Hello\n");
耗时 121,223 微秒。
是什么造成了这种明显的差异?
注意:我对每个测试取了 10 次测试的平均值。
默认情况下,cin/cout浪费时间与 C 库的 stdio 缓冲区同步,因此您可以自由地将对 scanf/printf 的调用与对 cin/cout 的操作混合使用。
关闭它
std::ios_base::sync_with_stdio(false);
还有很多C++教程告诉你写cout << endl而不是cout << '\n'。 但 endl 实际上更慢,因为它强制刷新,这通常是不必要的。 (如果您正在编写交互式进度条,则需要刷新,但在写入一百万行数据时则不需要。)写'\n'而不是 endl。
同样,由于 C++ 是面向对象的, cin 和 cout 也是对象,因此由于 object 绑定,整体时间增加了。
所以,一个简单的代码,“ std::ios_base::sync_with_stdio(false); ”可以使 cin/cout 比 printf/scanf 更快。 希望这对你有帮助
OOP 中的任何内容都将比纯函数式语言(如 C)中的等效项慢。OOP 附带 object 绑定的价格。 在这种情况下,内部同步/刷新通常会减慢 iostream i/o,Furthur,实际时间也因编译器而异。
在 C++ 程序中使用 scanf() 比使用 cin 更快?
为了更清楚起见,请查看此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.