简体   繁体   English

如何将数据复制到另一个向量?

[英]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 ? AV如何复制到CV

If I have the same using an array of double s (ie, double[] ) it takes more (tried with a profiler on MSVC and /Oi ): 如果我使用double s数组(即double[] ),则需要更多(在MSVC和/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? 我怎么能用C ++数组标准做同样的事情?

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. 我希望有一个强大的编译器来优化你的循环到一个不需要计数器和单个值副本的memcpy 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). 我肯定希望矢量副本能够做到这一点(因为无论谁编写了vector实现都很聪明并且会发现这个机会)。

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 . 如果要尽快复制double[]内容,请使用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 😟). 如果由于某种原因它不是,你也可以尝试直接memcpy (虽然这消除了类型安全😟)。


Why is memcpy faster? 为什么memcpy更快?

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. 在这种情况下,“计算机”是标准库实现,编译器和CPU的无定形伙伴关系。

You can achieve similar brevity and readability with arrays using a standard algorithm: 使用标准算法,您可以使用数组实现类似的简洁性和可读性:

std::copy(A, A + MAX_BUFFER, B);

As far speed is concerned, it depends on how the standard library is implemented, and how the compiler optimizes your loop. 就速度而言,它取决于标准库的实现方式,以及编译器如何优化循环。

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

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