C++ STL insert和emplace性能对比

 

 

 

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值