Skip to content

Instantly share code, notes, and snippets.

@BillyONeal
Created September 19, 2018 02:29
Show Gist options
  • Select an option

  • Save BillyONeal/8ed4016994e8fc7fe4916af4694d3f97 to your computer and use it in GitHub Desktop.

Select an option

Save BillyONeal/8ed4016994e8fc7fe4916af4694d3f97 to your computer and use it in GitHub Desktop.
// compile with:
// release: cl /EHsc /W4 /WX /std:c++latest /Festable_sort /MD /O2 .\sort.cpp
#include <stddef.h>
#include <stdio.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <execution>
#include <ratio>
#include <charconv>
#include <vector>
using namespace std; // sorry Titus
using namespace std::chrono;
const int iterationCount = 10;
void print_results(const char *const tag, const vector<double>& sorted,
high_resolution_clock::time_point startTime,
high_resolution_clock::time_point endTime) {
printf("%s: Lowest: %g Highest: %g Time: %fms\n", tag, sorted.front(),
sorted.back(),
duration_cast<duration<double, milli>>(endTime - startTime).count());
}
int main(int argc, char **argv) {
random_device rd;
if (argc != 2) { return 1; }
size_t testSize;
auto [ptr, ec] = from_chars(argv[1], argv[1] + strlen(argv[1]), testSize);
if (ec != errc{}) {
printf("Bad %s parse as integer.\n", argv[1]);
return 2;
}
// generate some random doubles:
printf("Testing with %zu doubles...\n", testSize);
vector<double> doubles(testSize);
for (auto& d : doubles) {
d = static_cast<double>(rd());
}
// time how long it takes to sort them:
high_resolution_clock::duration serialTime{};
for (int i = 0; i < iterationCount; ++i)
{
vector<double> sorted(doubles);
const auto startTime = high_resolution_clock::now();
sort(sorted.begin(), sorted.end());
const auto endTime = high_resolution_clock::now();
serialTime += endTime - startTime;
print_results("Serial", sorted, startTime, endTime);
}
// ... and in parallel:
high_resolution_clock::duration parallelTime{};
for (int i = 0; i < iterationCount; ++i)
{
vector<double> sorted(doubles);
const auto startTime = high_resolution_clock::now();
sort(std::execution::par, sorted.begin(), sorted.end());
const auto endTime = high_resolution_clock::now();
parallelTime += endTime - startTime;
print_results("Parallel", sorted, startTime, endTime);
}
const char * direction;
double times;
if (serialTime < parallelTime) {
times = static_cast<double>(parallelTime.count()) / serialTime.count();
direction = "slower";
} else {
times = static_cast<double>(serialTime.count()) / parallelTime.count();
direction = "faster";
}
printf("Serial total: %lld Parallel total: %lld\n", serialTime.count(), parallelTime.count());
printf("Parallel was %f times %s\n", times, direction);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment