简体   繁体   English

对于 output,std::copy 是否比 std::cout 快?

[英]is std::copy faster than std::cout for output?

std::vector<int> v{2,4,6,8,10,12,14,16,18,20};

// print the numbers
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';

here std::copy is used to write to std out.这里 std::copy 用于写入标准输出。 Is this faster than using std::cout for the vector elements in a for loop like这比在 for 循环中对向量元素使用 std::cout 更快吗

for(auto element: v) std::cout << element << " ";

I could't find much information about how they would write to output buffers for both.我找不到太多关于他们如何写入 output 缓冲区的信息。

To give an rough idea on the relative performance of the two, see the benchmark results here: http://quick-bench.com/wGYYPBXEgvLrkyp5gpJOnIpt7A4要大致了解两者的相对性能,请在此处查看基准测试结果: http://quick-bench.com/wGYYPBXEgvLrkyp5gpJOnIpt7A4

I had to output to a std::stringstream instead of std::cout to keep quick-bench happy.我不得不将 output 转换为std::stringstream而不是std::cout以保持快速工作台的快乐。 It gives some insight on the raw performance of the underlying implementations, but not on how they crossplay with a highly OS dependent output stream like std::cout .它提供了一些关于底层实现的原始性能的见解,但没有关于它们如何与高度依赖操作系统的 output stream (如std::cout )交互。

So it is hard to come to any definitive conclusions based on such a simple benchmark alone.因此,仅基于这样一个简单的基准很难得出任何明确的结论。 I would take from this that in reality there is most likely not enough difference between the two approaches to prefer one over the other from a performance perspective.我认为实际上这两种方法之间很可能没有足够的差异,从性能的角度来看,更喜欢其中一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM