cout 或 printf 两者中哪一个具有更快的执行速度 C++?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/896654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:50:26  来源:igfitidea点击:

cout or printf which of the two has a faster execution speed C++?

c++

提问by pirate

I have been coding in C++ for a long time. I always wondered which has a faster execution speed printfor cout?

我已经用 C++ 编码很长时间了。我一直想知道哪个执行速度更快printfcout

Situation: I am designing an application in C++ and I have certain constraints such as time limit for execution. My application has loads printing commands on the console. So which one would be preferable printfor cout?

情况:我正在用 C++ 设计一个应用程序,我有一些限制,例如执行时间限制。我的应用程序在控制台上加载了打印命令。那么,哪一个是最好printf还是cout

回答by Hexagon

Each has its own overheads. Depending on what you print, either may be faster.

每个都有自己的开销。根据您打印的内容,两者都可能更快。

Here are two points that come to mind -

想到的有两点——

printf() has to parse the "format" string and act upon it, which adds a cost.
cout has a more complex inheritance hierarchy and passes around objects.

printf() 必须解析“格式”字符串并对其进行操作,这会增加成本。
cout 具有更复杂的继承层次结构并传递对象。

In practice, the difference shouldn't matter for all but the weirdest cases. If you think it really matters - measure!

在实践中,除了最奇怪的情况外,差异应该无关紧要。如果您认为这真的很重要 - 衡量!

EDIT-
Oh, heck, I don't believe I'm doing this, but for the record, on my very specific test case, with my very specific machine and its very specific load, compiling in Release using MSVC -

编辑-
哦,哎呀,我不相信我在做这个,但为了记录,在我非常具体的测试用例中,使用我非常具体的机器及其非常具体的负载,使用 MSVC 在 Release 中编译 -

Printing 150,000 "Hello, World!"s (without using endl) takes about -
90ms for printf(), 79ms for cout.

打印 150,000 个“Hello, World!”(不使用 endl)大约需要 -
printf() 90ms,cout 79ms。

Printing 150,000 random doubles takes about -
3450ms for printf(), 3420ms for cout.

打印 150,000 个随机双打大约需要 -
printf() 3450ms,cout 3420ms。

(averaged over 10 runs).

(平均超过 10 次运行)。

The differences are so slim this probably means nothing...

差异如此之小,这可能意味着什么......

回答by Noldorin

Do you really need to care which has a faster execution speed? They are both used simply for printing text to the console/stdout, which typically isn't a task that demands ultra-high effiency. For that matter, I wouldn't imagine there to be a large difference in speed anyway (though one mightexpect printfto be marginally quicker because it lacks the minor complications of object-orientedness). Yet given that we're dealing with I/O operations here, even a minor difference would probably be swamped by the I/O overhead. Certainly, if you compared the equivalent methods for writing to files, that would be the case.

你真的需要关心哪个执行速度更快吗?它们都仅用于将文本打印到控制台/标准输出,这通常不是需要超高效率的任务。就此而言,我不认为速度会有很大差异(尽管人们可能期望printf稍微快一点,因为它缺乏面向对象的轻微并发症)。然而,鉴于我们在这里处理 I/O 操作,即使是很小的差异也可能会被 I/O 开销淹没。当然,如果您比较写入文件的等效方法,情况就会如此。

printfis simply the standard way to output text to stdout in C.
'cout' piping is simply the standard way to output text to stdout in C++.

printf只是在 C 中将文本输出到 stdout 的标准方法。
“cout”管道只是在 C++ 中将文本输出到 stdout 的标准方法。

Saying all this, there is a thread on the comp.lang.ccgroup discussing the same issue. Consensus does however seem to be that you should choose one over the other for reasons other than performance.

说了这么多,comp.lang.cc组上有一个线程在讨论同样的问题。然而,共识似乎是出于性能以外的原因,您应该选择一个而不是另一个。

回答by robermorales

The reason C++ cout is slow is the default sync with stdio.

C++ cout 慢的原因是与 stdio 的默认同步。

Try executing the following to deactivate this issue.

尝试执行以下操作来取消此问题。

ios_base::sync_with_stdio(false)

ios_base::sync_with_stdio(false)

http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/

http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/

http://msdn.microsoft.com/es-es/library/7yxhba01.aspx

http://msdn.microsoft.com/es-es/library/7yxhba01.aspx

回答by Daniel Earwicker

On Windows at least, writing to the console is a huge bottleneck, so a "noisy" console mode program will be far slower than a silent one. So on that platform, slight differences in the library functions used to address the console will probably make no significant difference in practice.

至少在 Windows 上,写入控制台是一个巨大的瓶颈,因此“嘈杂”的控制台模式程序将比静默程序慢得多。因此,在该平台上,用于处理控制台的库函数的细微差异在实践中可能不会产生显着差异。

On other platforms it may be different. Also it depends just how much console output you are doing, relative to other useful work.

在其他平台上可能会有所不同。此外,相对于其他有用的工作,这取决于您正在执行多少控制台输出。

Finally, it depends on your platform's implementation of the C and C++ I/O libraries.

最后,这取决于您的平台对 C 和 C++ I/O 库的实现。

So there is no general answer to this question.

所以这个问题没有普遍的答案。

回答by nhaa123

Performance is a non-issue for comparison; can't think of anything where it actually counts (developing a console-program). However, there's a few points you should take into account:

性能不是比较的问题;想不出它真正重要的地方(开发控制台程序)。但是,您应该考虑以下几点:

  • Iostreams use operator chaining instead of va_args. This means that your program can't crash because you passed the wrong number of arguments. This can happen with printf.

  • Iostreams use operator overloading instead of va_args -- this means your program can't crash because you passed an int and it was expecting a string. This can happen with printf.

  • Iostreams don't have native support for format strings (which is the major root cause of #1 and #2). This is generally a good thing, but sometimes they're useful. The Boost format library brings this functionality to Iostreams for those who need it with defined behavior (throws an exception) rather than undefined behavior (as is the case with printf). This currently falls outside the standard.

  • Iostreams, unlike their printf equivilants, can handle variable length buffers directly themselves instead of you being forced to deal with hardcoded cruft.

  • Iostreams 使用运算符链接而不是 va_args。这意味着您的程序不会因为传递了错误数量的参数而崩溃。这可能发生在 printf 中。

  • Iostreams 使用运算符重载而不是 va_args——这意味着你的程序不会因为你传递了一个 int 而它期望一个字符串而崩溃。这可能发生在 printf 中。

  • Iostreams 没有对格式字符串的原生支持(这是 #1 和 #2 的主要原因)。这通常是一件好事,但有时它们很有用。Boost 格式库将此功能带入 Iostreams,供那些需要它的人使用已定义的行为(抛出异常)而不是未定义的行为(如 printf 的情况)。这目前不在标准范围内。

  • iostreams,不像他们的 printf equivilants,可以直接自己处理可变长度的缓冲区,而不是你被迫处理硬编码的 cruft。

Go for cout.

去考特。

回答by Michael Burr

Another Stack Overflow question addressed the relative speed of C-style formatted I/O vs. C++ iostreams:

另一个堆栈溢出问题解决了 C 样式格式化 I/O 与 C++ iostreams 的相对速度:

Note, however, that the benchmarks discussed were for formatting to memory buffers. I'd guess that if you're actually performing the I/O to a console or file that the relative speed differences would be much smaller due to the I/O taking more of the overall time.

但是请注意,所讨论的基准测试是针对内存缓冲区的格式化。我猜想,如果您实际上是对控制台或文件执行 I/O,那么由于 I/O 占用的总时间更多,因此相对速度差异会小得多。

回答by Scott Dillman

I recently was working on a C++ console application on windows that copied files using CopyFileEx and was echoing the 'to' and 'from' paths to the console for each copy and then displaying the average throughput at the end of the operation.

我最近在 Windows 上开发一个 C++ 控制台应用程序,该应用程序使用 CopyFileEx 复制文件,并将“to”和“from”路径回显到每个副本的控制台,然后在操作结束时显示平均吞吐量。

When I ran the console application using printf to echo out the strings I was getting 4mb/sec, when replacing the printf with std::cout the throughput dropped to 800kb/sec.

当我使用 printf 运行控制台应用程序来回显我得到 4mb/sec 的字符串时,当用 std::cout 替换 printf 时,吞吐量下降到 800kb/sec。

I was wondering why the std::cout call was so much more expensive and even went so far as to echo out the same string on each copy to get a better comparison on the calls. I did multiple runs to even out the comparison, but the 4x difference persisted.

我想知道为什么 std::cout 调用要贵得多,甚至在每个副本上回显相同的字符串以获得更好的调用比较。我进行了多次运行以平衡比较,但 4 倍的差异仍然存在。

Then I found thisanswer on stackoverflow..

然后我在stackoverflow上找到了这个答案..

Switching on buffering for stdout did the trick, now my throughput numbers for printf and std::cout are pretty much the same.

打开 stdout 的缓冲就成功了,现在我的 printf 和 std::cout 吞吐量数字几乎相同。

I have not dug any deeper into how printf and cout differ in console output buffering, but setting the output buffer before I begin writing to the console solved my problem.

我没有深入研究 printf 和 cout 在控制台输出缓冲方面的不同之处,但是在我开始写入控制台之前设置输出缓冲区解决了我的问题。

回答by ndrewxie

Why don't you do an experiment? On average for me, printing the string helloperson;\n using printf takes, on average, 2 clock ticks, while cout using endl takes a huge amount of time - 1248996720685 clock ticks. Using cout with "\n" as the newline takes only 41981 clock ticks. The short URL for my code is below:

你为什么不做一个实验?对我来说,平均而言,打印字符串 helloperson;\n 使用 printf 平均需要 2 个时钟滴答,而使用 endl 的 cout 需要大量时间 - 1248996720685 个时钟滴答。使用带有 "\n" 的 cout 作为换行符只需要 41981 个时钟滴答。我的代码的短网址如下:

cpp.sh/94qoj

cpp.sh/94qoj

link may have expired.

链接可能已过期。

To answer your question, printf is faster.

要回答您的问题, printf 更快。

#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int main()
{
  clock_t one;
  clock_t two;
  clock_t averagePrintf;
  clock_t averageCout;
  clock_t averagedumbHybrid;
  for (int j = 0; j < 100; j++) {
    one = clock();
    for (int d = 0; d < 20; d++) {
      printf("helloperson;");
      printf("\n");
    }
    two = clock();
    averagePrintf += two-one;

    one = clock();
    for (int d = 0; d < 20; d++) {
      cout << "helloperson;";
      cout << endl;
    }
    two = clock();
    averageCout += two-one;

    one = clock();
    for (int d = 0; d < 20; d++) {
      cout << "helloperson;";
      cout << "\n";
    }
    two = clock();
    averagedumbHybrid += two-one;
  }
  averagePrintf /= 100;
  averageCout /= 100;
  averagedumbHybrid /= 100;
  cout << "printf took " << averagePrintf << endl;
  cout << "cout took " << averageCout << endl;
  cout << "hybrid took " << averagedumbHybrid << endl;
}

Yes, I did use the word dumb. I first made it for myself, thinking that the results were crazy, so I searched it up, which ended up with me posting my code.

是的,我确实使用了愚蠢这个词。我先是自己做的,觉得结果很疯狂,所以我搜索了它,最后我发布了我的代码。

Hope it helps, Ndrewffght

希望它有所帮助,Ndrewffght

回答by sybreon

If you're using C++, you should use coutinstead as printfbelongs to the C family of functions. There are many improvements made for coutthat you may benefit from. As for speed, it isn't an issue as console I/O is going to be slow anyway.

如果您使用C ++,你应该使用cout,而不是作为printf属于C家族的功能。有许多改进可以cout让您受益。至于速度,这不是问题,因为控制台 I/O 无论如何都会变慢。

回答by PowerApp101

In practical terms I have always found printf to be faster than cout. But then again, cout does a lot more for you in terms of type safety. Also remember printf is a simple function whereas cout is an object based on a complex streams hierarchy, so it's not really fair to compare execution times.

实际上,我一直发现 printf 比 cout 快。但话又说回来,cout 在类型安全方面为您做了更多工作。还要记住 printf 是一个简单的函数,而 cout 是一个基于复杂流层次结构的对象,因此比较执行时间并不公平。