is std::copy faster than std::cout for output?

非 Y 不嫁゛ 提交于 2021-02-11 12:01:15

问题


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. Is this faster than using std::cout for the vector elements in a for loop like

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

I could't find much information about how they would write to output buffers for both.


回答1:


To give an rough idea on the relative performance of the two, see the benchmark results here: http://quick-bench.com/wGYYPBXEgvLrkyp5gpJOnIpt7A4

I had to output to a std::stringstream instead of std::cout to keep quick-bench happy. 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.

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.



来源:https://stackoverflow.com/questions/58621314/is-stdcopy-faster-than-stdcout-for-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!