Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2008-06-24 11:37:18


On Jun 23, 2008, at 3:54 PM, David Abrahams wrote:

> I haven't formed an opinion yet, but the fact remains that swapping a
> boost::array would have very different efficiency characteristics from
> swapping the analogous std::vector, so we ought to think it through
> carefully.

If it helps, here is a test program using gcc 4.0.1:

#include <iostream>
#include <vector>
#include <tr1/array>
#include <ctime>

template <class T, std::size_t N>
void
swap1(std::tr1::array<T, N>& a, std::tr1::array<T, N>& b)
{
     std::tr1::array<T, N> temp(a);
     a = b;
     b = temp;
}

template <class T, std::size_t N>
void
swap2(std::tr1::array<T, N>& a, std::tr1::array<T, N>& b)
{
     std::swap_ranges(a.begin(), a.end(), b.begin());
}

int main()
{
     std::tr1::array<std::vector<int>, 1000> a;
     for (unsigned i = 0; i < a.size(); ++i)
         a[i] = std::vector<int>(10000);
     std::tr1::array<std::vector<int>, 1000> b(a);
     std::clock_t t1 = std::clock();
     swap1(a, b);
     std::clock_t t2 = std::clock();
     std::cout << "swap1 time is " << double(t2 - t1) / CLOCKS_PER_SEC
<< " seconds\n";
     t1 = std::clock();
     swap2(a, b);
     t2 = std::clock();
     std::cout << "swap2 time is " << double(t2 - t1) / CLOCKS_PER_SEC
<< " seconds\n";
}

On my machine:

$ g++ -O3 test.cpp
$ ./a.out
swap1 time is 0.172796 seconds
swap2 time is 1.3e-05 seconds

I also note that swap1 can throw exceptions and swap2 can't. I also
note that move semantics will greatly speed swap1, and make it
nothrow, but I still expect swap1 with move semantics to be about
twice as slow as swap2.

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk