为什么移动构造函数更快?

问题描述 投票:2回答:1

我有一个非常简单的测试用例,其中一个Geometry类包含一个非常大的std :: vector。我正在比较复制/移动构造函数的速度:

class Geometry
{
public:
    Geometry(size_t size) : m_data(size) {}

    Geometry(const Geometry& other) : m_data(other.m_data)
    { std::cout << "Copy constructor" << std::endl; }

    Geometry(Geometry&& other) noexcept : m_data(std::move(other.m_data))
    { std::cout << "Move constructor" << std::endl; }

private:
    std::vector<double> m_data;
};

int main()
{
    Geometry geometry(1000000000);

    {
        ScopedTimer scopedTimer("copy constructor");
        Geometry geometry2(geometry);
    }

    {
        ScopedTimer scopedTimer("move constructor");
        Geometry geometry2(std::move(geometry));
    }
}

我期望复制构造函数非常慢,并且移动构造函数几乎是瞬时的,因为它只需要将句柄交换到底层的矢量资源。但是,这不是我在这里观察到的(ScopedTimer只是一个基于std :: chrono的简单计时器,它返回构造和销毁之间的持续时间)。这是我在发布配置中获得的输出(在调试配置中观察到类似的趋势):

Copy constructor
6832 ms copy constructor
Move constructor
2605 ms move constructor

移动构造函数快三倍,这更好,但不是我期望的。为什么不快呢?我期待移动构造函数为O(1)。为什么更大的矢量大小需要更长的时间?代码不需要分配任何东西等等。我错过了什么吗?

c++ performance move semantics move-constructor
1个回答
2
投票

您正在测量矢量销毁时间。没有它,移动构造函数即使在调试模式下也没有时间:

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <chrono>

class ScopedTimer
{
    std::string m_text;
    ::std::chrono::high_resolution_clock::time_point start;
    public: ScopedTimer(::std::string const & text):
    m_text{text}, start{::std::chrono::high_resolution_clock::now()} {}

    public: void Report(void)
    {
        auto const end{::std::chrono::high_resolution_clock::now()};
        ::std::cout << m_text << " " << ::std::chrono::duration_cast<::std::chrono::milliseconds>(end - start).count() << ::std::endl;
    }
};


class Geometry
{
public:
    Geometry(size_t size) : m_data(size) {}

    Geometry(const Geometry& other) : m_data(other.m_data)
    { std::cout << "Copy constructor" << std::endl; }

    Geometry(Geometry&& other) noexcept : m_data(std::move(other.m_data))
    { std::cout << "Move constructor" << std::endl; }

private:
    std::vector<double> m_data;
};

int main()
{
    Geometry geometry(1000000000);
    {
        ScopedTimer scopedTimer("copy constructor");
        {
            Geometry geometry2(geometry);
            scopedTimer.Report();
        }
        scopedTimer.Report();
    }
    {
        ScopedTimer scopedTimer("move constructor");
        {
            Geometry geometry2(std::move(geometry));
            scopedTimer.Report();
        }
        scopedTimer.Report();
    }
    return 0;
}

复制构造函数 复制构造函数5099 复制构造函数6526 移动构造函数 移动构造函数0 移动构造函数1319

© www.soinside.com 2019 - 2024. All rights reserved.