Skip to content

Instantly share code, notes, and snippets.

@raul-hc
Created November 20, 2016 22:04
Show Gist options
  • Save raul-hc/a427b2f602a2c5cd46f4da0d803542ca to your computer and use it in GitHub Desktop.
Save raul-hc/a427b2f602a2c5cd46f4da0d803542ca to your computer and use it in GitHub Desktop.
Sorted array processing - C++
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// The next loop runs faster because we are using a sorted array
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment