Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <chrono>
#include <memory>
#include <thread>
#include <new>
using namespace std;
const int SIZE = 2000000;
const int ALLOC_SIZE[] = { 10, 100, 1000, 100, 10, 100, 1000, 10000, 10, 100 };
const int ALLOC_LEN = sizeof(ALLOC_SIZE) / sizeof(int);
void test_cpp()
{
auto tm0 = chrono::high_resolution_clock::now();
vector<thread> v;
for (int i = 0; i < 8; ++i) {
thread tr([]{
for (int c = 1; c < SIZE; ++c) {
auto a = make_shared<string>();
const int N = c % ALLOC_LEN;
a->reserve(ALLOC_SIZE[N]);
}
});
v.push_back(move(tr));
}
for (auto &t : v) {
t.join();
}
auto tm1 = chrono::high_resolution_clock::now();
cout << chrono::duration_cast<chrono::milliseconds>(tm1 - tm0).count() << ", ";
}
void test_c()
{
auto tm0 = chrono::high_resolution_clock::now();
vector<thread> v;
for (int i = 0; i < 16; ++i) {
thread tr([]{
for (int c = 1; c < SIZE; ++c) {
const int N = c % ALLOC_LEN;
auto a = (char *)malloc(ALLOC_SIZE[N]);
free(a);
}
});
v.push_back(move(tr));
}
for (auto &t : v) {
t.join();
}
auto tm1 = chrono::high_resolution_clock::now();
cout << chrono::duration_cast<chrono::milliseconds>(tm1 - tm0).count() << ", ";
}
int main()
{
cout << "[std::string alloc]" << endl;
{
function<void()> f = test_cpp;
for (int i = 0; i < 5; ++i) {
f();
}
cout << endl;
}
cout << "[malloc()] " << endl;
{
function<void()> f = test_c;
for (int i = 0; i < 5; ++i) {
f();
}
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment