在 C++ 中复制数组的最快可移植方法是什么 [英] What is the fastest portable way to copy an array in C++

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

问题描述

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

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

  1. memcpy
  2. std::复制
  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天全站免登陆