Skip to content

Instantly share code, notes, and snippets.

@BillyONeal
Created June 3, 2017 02:25
Show Gist options
  • Save BillyONeal/84577fcef067c1c6d6f6410512e86b46 to your computer and use it in GitHub Desktop.
Save BillyONeal/84577fcef067c1c6d6f6410512e86b46 to your computer and use it in GitHub Desktop.
std::next benchmark
#include <stdio.h>
#include <algorithm>
#include <chrono>
#include <functional>
#include <iterator>
#include <random>
#include <vector>
using namespace std;
using namespace std::chrono;
template<class _FwdIt>
_FwdIt _Next(_FwdIt _First)
{
return (++_First);
}
void print_time(const char * const test, high_resolution_clock::time_point start,
high_resolution_clock::time_point stop) {
long long result = static_cast<long long>(duration_cast<milliseconds>(stop - start).count());
printf("%40s took %10lldms\n", test, result);
}
constexpr size_t dataSize = 100'000;
constexpr size_t iterations = 10;
int main() {
vector<unsigned int> sourceData(dataSize);
vector<unsigned int> targetData(dataSize);
random_device rd;
generate(sourceData.begin(), sourceData.end(), ref(rd));
const auto start = high_resolution_clock::now();
for (size_t iter = 0; iter < iterations; ++iter) {
auto beg = sourceData.begin();
for (size_t ch = 0; ch < dataSize; ++ch) {
targetData[ch] = *beg;
++beg;
}
}
const auto afterControl = high_resolution_clock::now();
print_time("increment in place (control)", start, afterControl);
for (size_t iter = 0; iter < iterations; ++iter) {
auto beg = sourceData.begin();
for (size_t ch = 0; ch < dataSize; ++ch) {
targetData[ch] = *beg;
beg = next(beg);
}
}
const auto afterNext = high_resolution_clock::now();
print_time("std::next", afterControl, afterNext);
for (size_t iter = 0; iter < iterations; ++iter) {
auto beg = sourceData.begin();
for (size_t ch = 0; ch < dataSize; ++ch) {
targetData[ch] = *beg;
beg = _Next(beg);
}
}
const auto after_Next = high_resolution_clock::now();
print_time("std::next with special case", afterNext, after_Next);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment