繁体   English   中英

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

[英]Why isn't move constructor faster?

我有一个非常简单的测试用例,其中一个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)。 为什么更大的矢量尺寸需要更长的时间? 代码不需要分配任何东西等。我错过了什么吗?

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

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM