Last active
December 1, 2020 19:57
-
-
Save kd9f9/62a8273ce25aaab06562e76b4871ca0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source code for the post https://cppbenchmarks.wordpress.com/2020/08/25/benchmarking-stdvector-and-stdlist-sorting-performance/ | |
#include <vector> | |
#include <list> | |
#include <iostream> | |
#include <chrono> | |
#include <algorithm> | |
struct BloatedInt { | |
BloatedInt(int i) : key(i) {} | |
int32_t key; | |
int32_t bloat[200]; | |
}; | |
using ElementType = BloatedInt; | |
const auto comp = [](const BloatedInt &a, const BloatedInt &b) { return a.key < b.key; }; | |
template <int nElements> std::chrono::milliseconds benchmarkVectorSort() { | |
srand(0); | |
std::vector<ElementType> *vector = new std::vector<ElementType>(); | |
for (int i = 0; i < nElements; ++i) { | |
(*vector).push_back(ElementType(rand())); | |
} | |
const auto start = std::chrono::steady_clock::now(); | |
std::sort(std::begin(*vector), std::end(*vector), comp); | |
const auto end = std::chrono::steady_clock::now(); | |
delete vector; | |
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start); | |
} | |
template <int nElements> std::chrono::milliseconds benchmarkListSort() { | |
srand(0); | |
std::list<ElementType> *list = new std::list<ElementType>(); | |
for (int i = 0; i < nElements; ++i) { | |
(*list).push_back(ElementType(rand())); | |
} | |
const auto start = std::chrono::steady_clock::now(); | |
list->sort(comp); | |
const auto end = std::chrono::steady_clock::now(); | |
delete list; | |
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start); | |
} | |
void getFastestRun(const int iterations, auto f) { | |
std::chrono::milliseconds minDuration{999999}; | |
for (int i = 0; i < iterations; ++i) { | |
const std::chrono::milliseconds duration = f(); | |
if (duration.count() < minDuration.count()) { | |
minDuration = duration; | |
} | |
} | |
std::cout << minDuration.count() << "ms"; | |
} | |
auto main() -> int { | |
constexpr int nElements = 300000; | |
constexpr int nIterations = 500; | |
std::cout << "vector: "; | |
getFastestRun(nIterations, []() { return benchmarkVectorSort<nElements>(); }); | |
std::cout << "\nlist: "; | |
getFastestRun(nIterations, []() { return benchmarkListSort<nElements>(); }); | |
std::cout << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment