用C ++复制数组的最快便携式方法是什么 [英] What is the fastest portable way to copy an array in C++

查看:450
本文介绍了用C ++复制数组的最快便携式方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题困扰了我一段时间.我正在考虑的可能性是

This question has been bothering me for some time. The possibilities I am considering are

  1. memcpy
  2. std :: copy
  3. cblas_dcopy

有人对这三者的利弊有什么线索吗?也欢迎其他建议.

Does anyone have any clue on what the pros and cons are with these three? Other suggestions are also welcome.

推荐答案

在C ++中,除非有充分的理由,否则默认情况下应使用std :: copy.原因是C ++类通过复制构造函数和复制赋值运算符定义了自己的复制语义,在列出的操作中,只有std :: copy遵守这些约定.

In C++ you should use std::copy by default unless you have good reasons to do otherwise. The reason is that C++ classes define their own copy semantics via the copy constructor and copy assignment operator, and of the operations listed, only std::copy respects those conventions.

memcpy()使用原始的按字节的数据副本(尽管可能对缓存行大小进行了优化,等等),并且忽略了C ++复制语义(毕竟是C函数).

memcpy() uses raw, byte-wise copy of data (though likely heavily optimized for cache line size, etc.), and ignores C++ copy semantics (it's a C function, after all...).

cblas_dcopy()是一个专用函数,用于使用双精度浮点值的线性代数例程.它可能擅长于此,但不应被视为通用.

cblas_dcopy() is a specialized function for use in linear algebra routines using double precision floating point values. It likely excels at that, but shouldn't be considered general purpose.

如果您的数据是简单" POD类型的结构数据或原始基础类型数据,则memcpy可能会尽可能快.在这种情况下,std :: copy可能会被优化为使用memcpy,因此您永远不会知道它们之间的区别.

If your data is "simple" POD type struct data or raw fundamental type data, memcpy will likely be as fast as you can get. Just as likely, std::copy will be optimized to use memcpy in these situations, so you'll never know the difference.

简而言之,请使用std :: copy().

In short, use std::copy().

这篇关于用C ++复制数组的最快便携式方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆