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

2022-01-04 00:00:00 io c++ cout

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

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

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

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 printf or cout?

推荐答案

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

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

这里有两点想到-

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

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.

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

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

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

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 -

打印 150,000 个Hello, World!"(不使用 endl)大约需要 -
printf() 为 90 毫秒,cout 为 79 毫秒.

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

打印 150,000 个随机双打大约需要 -
printf() 为 3450 毫秒,cout 为 3420 毫秒.

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

(平均超过 10 次运行).

(averaged over 10 runs).

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

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

相关文章