【发布时间】:2015-02-25 19:00:08
【问题描述】:
给定两个 std::vector v1, v2.
我想知道使用 std::swap(v1, v2) 比 v1.swap(v2) 有什么好处。
关于性能的观点,我已经实现了一个简单的测试代码(我不确定它是否相关):
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>
#define N 100000
template<typename TimeT = std::chrono::microseconds>
struct Timer
{
template<typename F, typename ...Args>
static typename TimeT::rep exec(F func, Args&&... args)
{
auto start = std::chrono::steady_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now() - start);
return duration.count();
}
};
void test_std_swap(std::vector<double>& v1, std::vector<double>& v2)
{
for (int i = 0; i < N; i ++)
{
std::swap(v1,v2);
std::swap(v2,v1);
}
}
void test_swap_vector(std::vector<double>& v1, std::vector<double>& v2)
{
for (int i = 0; i < N; i ++)
{
v1.swap(v2);
v2.swap(v1);
}
}
int main()
{
std::vector<double> A(1000);
std::generate( A.begin(), A.end(), [&]() { return std::rand(); } );
std::vector<double> B(1000);
std::generate( B.begin(), B.end(), [&]() { return std::rand(); } );
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B) << std::endl;
}
根据输出,如果没有优化,vector::swap 似乎更快-O0。 输出为(以微秒为单位):
20292
16246
16400
13898
与 -O3 没有明显的区别。
752
752
752
760
【问题讨论】:
-
一般性以外。
-
@DietmarKühl 是的,绝对是。我的意思是“超载”,但现在编辑我的第一条评论为时已晚。