欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ STL insert和emplace性能对比

程序员文章站 2022-03-01 22:18:39
...

 

 

 

#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
 
class Dew
{
  public:
    Dew(int _a, int _b, int _c)
      : a(_a), b(_b), c(_c)
    {
        data = new char[100];
    }
    Dew(const Dew& source): a(source.a), b(source.b), c(source.c)
    {
        if(source.data != nullptr)
        {
            data = new char[100];
        }
    }
 
    bool operator<(const Dew &other) const
    {
      if (a < other.a)
        return true;
      if (a == other.a && b < other.b)
        return true;
      return (a == other.a && b == other.b && c < other.c);
    }
    ~Dew()
    {
        if(data != nullptr)
        {
            delete[] data;
            data = nullptr;
            
        }
    }
    int a;
    int b;
    int c;
    char* data;
};
 
const int nof_operations = 128;
 
int set_emplace() {
    std::set<Dew> set;
    for(int i = 0; i < nof_operations; ++i)
        for(int j = 0; j < nof_operations; ++j)
            for(int k = 0; k < nof_operations; ++k)
              set.emplace(i, j, k);
 
    return set.size();
}
 
int set_insert() {
    std::set<Dew> set;
    for(int i = 0; i < nof_operations; ++i)
        for(int j = 0; j < nof_operations; ++j)
            for(int k = 0; k < nof_operations; ++k)
              set.insert(Dew(i, j, k));
 
    return set.size();
}
 
void timeit(std::function<int()> set_test, std::string what = "") {
  auto start = std::chrono::system_clock::now();
  int setsize = set_test();
  auto stop = std::chrono::system_clock::now();
  std::chrono::duration<double, std::milli> time = stop - start;
  if (what.size() > 0 && setsize > 0) {
    std::cout << std::fixed << std::setprecision(2)
        << time.count() << "  ms for " << what << '\n';
  }
}
 
int main()
{
  timeit(set_insert, "insert");
  timeit(set_emplace, "emplace");
  timeit(set_insert, "insert");
  timeit(set_emplace, "emplace");
}

输出如下

1599.82  ms for insert
969.08  ms for emplace
1090.83  ms for insert
1021.48  ms for emplace
相关标签: C++ c++