Skip to content

Instantly share code, notes, and snippets.

@kd9f9
Last active October 11, 2020 14:59
Show Gist options
  • Save kd9f9/1b3c3a9fdc399843b75cdc35673f2d46 to your computer and use it in GitHub Desktop.
Save kd9f9/1b3c3a9fdc399843b75cdc35673f2d46 to your computer and use it in GitHub Desktop.
// 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>
using ElementType = int32_t;
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));
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();
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