Skip to content

Instantly share code, notes, and snippets.

@cwsmith
Last active November 29, 2018 13:05
Show Gist options
  • Save cwsmith/50d9aee51625b89074f93507b68ebec7 to your computer and use it in GitHub Desktop.
Save cwsmith/50d9aee51625b89074f93507b68ebec7 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <chrono>
#include <cassert>
using namespace std;
// Don't change this function!
void slide_ref(const int n, double* in, double* out) {
auto start = chrono::steady_clock::now();
out[0] = out[1] = out[n-2] = out[n-1] = 0;
for(int i=2; i<n-2; i++) {
out[i] = in[i-2] + in[i-1] + in[i] + in[i+1] + in[i+2];
}
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << chrono::duration <double, milli> (diff).count() << " ms\n";
}
// Please edit this function
void slide(const int n, double* in, double* out) {
auto start = chrono::steady_clock::now();
out[0] = out[1] = out[n-2] = out[n-1] = 0;
for(int i=2; i<n-2; i++) {
out[i] = in[i-2] + in[i-1] + in[i] + in[i+1] + in[i+2];
}
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << chrono::duration <double, milli> (diff).count() << " ms\n";
}
int main() {
const int n = 100*1024*1024;
double* in = new double[n];
for(int i=0; i<n; i++)
in[i] = i;
double* out = new double[n];
double* ref = new double[n];
// compute the sliding average such that
// out[i] = in[i-2] + in[i-1] + in[i] + in[i+1] + in[i+2]
// let the first two and last two entries of the output be zero
// out[0] = out[1] = out[n-2] = out[n-1] = 0;
slide_ref(n,in,ref); // reference solution
//write a faster version here!
slide(n,in,out);
for(int i=2; i<n-2; i++) {
if(ref[i]!=out[i]) {
cerr << "solution does not match at index " << i
<< "... exiting\n";
return 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment