通过值或通过引用返回类对象,这在这里会更快
Returning class object by value or pass by reference, which will be faster here
假设我有一个class
对象matrix
。对于add
和两个大元素的matrix
,我可以定义一个重载+
的运算符,或者定义一个像这些一样的函数Add
matrix operator + (const matrix &A, const matrix &B)
matrix C;
/* all required things */
for(int i .........){
C(i)=A(i)+B(i);
}
return C;
}
我打电话给
matrix D = A+B;
现在,如果我定义Add
函数,
void Add(const matrix &A, const matrix &B, matrix &C)
C.resize(); // according to dimensions of A, B
// for C.resize , copy constructor will be called.
/* all required things */
for(int i .........){
C(i)=A(i)+B(i);
}
}
我必须调用这个函数,比如
matrix D;
Add(A,B,D); //D=A+B
上述方法中的哪一种更快、更有效。我们应该使用哪一个?
- 在不使用任何工具的情况下,
- 类似于探查器(例如gprof),以查看在哪里花费了多少时间
- 也没有任何其他工具,如">valgrind+cachegrind",以查看在这两个功能中执行了多少操作
- 并且还忽略所有编译器优化,即使用CCD_
- 假设这两个函数中还有其他任何东西(表示为
/* all required things */
)都是微不足道的
那么,只要看看你的两个函数,就可以说,你的两种函数的复杂性都是O(n)
,因为你的两款函数大部分时间都在两个for
循环中。根据矩阵的大小,特别是如果它们真的很大,代码中的其他一切在降低速度时都是微不足道的。
所以,在我看来,你的问题归结为
- 需要多少时间,
- 调用
C
的构造函数 - 加上返回该CCD_ 13,与之相比
- 调用
- 需要多少时间,
- 为CCD_ 15调用CCD_
- 再加上调用CCD_ 16的复制构造函数
这可以使用std::clock()
或chrono
"粗略但相对快速"地进行测量,如多个答案所示。
#include <chrono>
auto t_start = std::chrono::high_resolution_clock::now();
matrix D = A+B; // To compare replace on 2nd run with this ---> matrix D; Add(A,B,D);
auto t_end = std::chrono::high_resolution_clock::now();
double elaspedTimeMs = std::chrono::duration<double, std::milli>(t_end-t_start).count();
不过,在我看来,如果你的矩阵很大,大部分时间都会进入for
循环。
p.s.过早的优化是万恶之源
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- File.cpp.o:OpenPose 标志 CMakeFiles/.. 的多重定义/main.cpp.o:首先在这里定
- 为什么thread_local变量在这里从未初始化?
- 为什么我必须在这里使用dynamic_cast
- C++ 获取函数在常量引用中按值返回的结果
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 为什么 C++20 中的 [[可能]] 属性在这里引发警告?
- 我在这里正确传递参数了吗?
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- 移动语义在这里如何工作?
- 如何在这里循环运行?
- 为什么枚举变量在这里是右值?
- 通过值或通过引用返回类对象,这在这里会更快
- 为什么 wx 在这里不使用引用,wx 的 API 和端口层如何交互?
- C++ - 引用和运算符=在这里做什么
- 我应该<T>在这里通过引用传递unique_ptr吗?
- 为什么我不能在这里通过引用传递类对象?