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 insert969.08 ms for emplace1090.83 ms for insert1021.48 ms for emplace
推荐阅读
-
[C++]阻塞和非阻塞的队列的性能对比(Non-BlockingQueue&BlockingQueue benchmark)
-
不同的数据库连接池(DBCP,C3P0,Druid,Hikari)下对mysql的随机update和insert性能对比
-
C++ STL 容器vector添加元素函数emplace_back()和push_back()的使用差异
-
c++中STL的push_back和emplace_back的区别
-
emplace_back和push_back性能对比
-
C++ STL vector添加元素之push_back()和emplace_back()的区别
-
[c++] insert和emplace的区别
-
C++ STL insert和emplace性能对比
-
STL中插入元素insert和emplace,效率