为何使用std::move未提升swap()函数性能?实测结果存疑
为何使用std::move未能提升swap()函数的性能?
按照相关文章所述,使用std::move可避免拷贝操作,进而提升函数性能。但我在Linux环境下通过VSCode+GCC9.4进行测试后,结果与文章内容不符。
测试代码如下:
#include <iostream> #include <chrono> template <typename T> void swap1(T& a, T& b) { T tmp(a); // 此时存在两份a的拷贝 a = b; // 此时存在两份b的拷贝 b = tmp; // 此时存在两份tmp(即原a)的拷贝 } template <typename T> void swap2(T& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); } int main() { int a = 10; int b = 20; int num = 100000; const auto& time_t1 = std::chrono::steady_clock::now(); for(int i = 0; i < num; i++){ swap1(a,b); } const auto& time_t2 = std::chrono::steady_clock::now(); double time_lf = (time_t2 - time_t1).count() / 1000000.0; std::cout<<"time_lf: "<<time_lf<<std::endl; const auto& time_t3 = std::chrono::steady_clock::now(); for(int i = 0; i < num; i++){ swap2(a,b); } const auto& time_t4 = std::chrono::steady_clock::now(); double time_move = (time_t4 - time_t3).count() / 1000000.0; std::cout<<"time_move: "<<time_move<<std::endl; return 0; }
输出结果为:
time_lf: 0.177079 time_move: 0.384381
请问为何使用std::move未能提升swap()函数的性能?
内容的提问来源于stack exchange,提问作者hitbuyi
相关产品推荐
相关产品推荐

