Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How vector copy data to another vector?

Let say I've this:

const int MAX_BUFFER = 1024;
std::vector<double> AV(MAX_BUFFER);
std::vector<double> CV{ AV };

How is AV copied into CV?

If I have the same using an array of doubles (i.e., double[]) it takes more (tried with a profiler on MSVC and /Oi):

for (int sampleIndex = 0; sampleIndex < MAX_BUFFER; sampleIndex++) {
    C[sampleIndex] = A[sampleIndex];
}

How does it copy faster? How can I do the same with C++ array standard?

like image 944
markzzz Avatar asked Apr 30 '26 16:04

markzzz


1 Answers

This is hard to answer with absolute certainty, as it depends on your toolchain and your optimisation levels and (to some degree) on fate.

I would perhaps expect a strong compiler to optimise your loop into a memcpy that does not require counters and individual value copies. Or perhaps not. Certainly it appears that yours isn't doing that.

I would definitely expect the vector copy to do that (because whoever wrote the vector implementation is clever and would have spotted this opportunity).

Ultimately you would have to read the implementation's source code to find out for sure.

If you want to copy your double[] contents as fast as possible, use std::copy.

This should perform that optimisation. Certainly it won't be any slower than your loop, and could be faster. If for some reason it isn't, you could also try a direct memcpy (though this eliminates type safety 😟).


Why is memcpy faster?

Computers are fast at blatting blocks of bytes in one go, as long as they know up-front that this is what you want to do.

In fact, this is a good lesson in writing code that "says what you mean" and lets the computer decide how to go about it, rather than spelling out the individual steps that you think the task requires and thus making it harder for the computer to do what you really meant in the best way possible.

In this context "the computer" is an amorphous partnership of standard library implementation, compiler, and CPU.

like image 146
Lightness Races in Orbit Avatar answered May 03 '26 07:05

Lightness Races in Orbit