0

I saw in this cppcon that make_unique/make_shared are supposed to be faster but in the following program I ran in VSCode and compiled with g++ gives me different result.

#include <chrono>
#include <memory>
#include <iostream>

size_t len = 10000000;
int main(int argc, char const *argv[])
{
  auto start = std::chrono::system_clock::now();
  for (size_t i = 0; i < len; i++)
  {
    int* tmp(new int(i));
    delete tmp;
  }
  std::chrono::duration<double> dur = std::chrono::system_clock::now() - start;
  std::cout << "int* = " << dur.count() << "\n";

  start = std::chrono::system_clock::now();
  for (size_t i = 0; i < len; i++)
  {
    std::unique_ptr<int> tmp(new int(i));
  }
  dur = std::chrono::system_clock::now() - start;
  std::cout << "std::unique_ptr = " << dur.count() << "\n";
  
  start = std::chrono::system_clock::now();
  for (size_t i = 0; i < len; i++)
  {
    std::unique_ptr<int> tmp = std::make_unique<int>(i);
  }
  dur = std::chrono::system_clock::now() - start;
  std::cout << "std::make_unique = " << dur.count() << "\n";
  
  start = std::chrono::system_clock::now();
  for (size_t i = 0; i < len; i++)
  {
    std::shared_ptr<int> tmp(new int(i));
  }
  dur = std::chrono::system_clock::now() - start;
  std::cout << "std::shared_ptr = " << dur.count() << "\n";
  
  start = std::chrono::system_clock::now();
  for (size_t i = 0; i < len; i++)
  {
    std::shared_ptr<int> tmp = std::make_shared<int>(i);
  }
  dur = std::chrono::system_clock::now() - start;
  std::cout << "std::make_shared = " << dur.count() << "\n";
  
  return 0;
}

Result:

int* = 0.709534
std::unique_ptr = 1.12149
std::make_unique = 1.14068
std::shared_ptr = 1.7354
std::make_shared = 2.13896

Can anyone please explain the mystery behind?

Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32
getsuha
  • 711
  • 6
  • 16

0 Answers0