问题
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