码迷,mamicode.com
首页 > 移动开发 > 详细

C++11:移动构造函数的测试

时间:2019-06-03 14:27:46      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:alt   adl   test   word   amp   stack   tdd   pac   col   

C++11:移动构造函数的测试

 代码如下:

#include <iostream>
#include <stddef.h>
#include <Windows.h>

using namespace std;

class CTest
{
private:
  std::size_t size;
  char* buffer;

public:
  CTest(std::size_t size) : size(size), buffer(nullptr)
  {
    buffer = new char[size];
  }

  ~CTest()
  {
    delete[] buffer;
  }

  CTest(const CTest& other) : size(other.size), buffer(nullptr)
  {
    buffer = new char[size];
  }

  CTest(CTest&& other) : size(other.size), buffer(other.buffer)
  {
    other.buffer = nullptr;
  }
};

template <typename Func>
__int64 Benchmark(Func f, size_t count)
{
//   LARGE_INTEGER m_liPerfFreq={0};
//   //获取每秒多少CPU Performance Tick
//   QueryPerformanceFrequency(&m_liPerfFreq); 
  LARGE_INTEGER li = {};
  QueryPerformanceCounter(&li);
  __int64 start = li.QuadPart;

  f(count);

  QueryPerformanceCounter(&li);
  return (li.QuadPart - start);//* 1000 / m_liPerfFreq.QuadPart;
}

void Alloc_Ref(size_t count)
{
  CTest t(1024);
  for(size_t i = 0; i < count; ++i)
    CTest c(t);
}

void Alloc_Move(size_t count)
{
  CTest t(1024);
  for(size_t i = 0; i < count; ++i)
    CTest c(std::move(t));
    //CTest c(CTest(1024));

}

int _tmain(int argc, _TCHAR* argv[])
{
  for(int i= 0; i<10 ;++i)
  {
    cout << "Move: "<< Benchmark(Alloc_Move, 1000000) << " ms." << endl;
    cout << "Ref:  " << Benchmark(Alloc_Ref, 1000000) << " ms." << endl;    
  }

  system("pause");
    return 0;
}

程序运行结果如下:

技术图片

结论:可见移动构造函数是拷贝构造函数的1-3倍。

参考链接:

VS 2010, Move constructor only reached after move() and slower than copy constructor?

C++11:移动构造函数的测试

标签:alt   adl   test   word   amp   stack   tdd   pac   col   

原文地址:https://www.cnblogs.com/2018shawn/p/10967077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!