Skip to content

Instantly share code, notes, and snippets.

@pykello

pykello/sum.cpp Secret

Last active March 28, 2022 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pykello/c453e0ba413932ccb7d09aa327b75aca to your computer and use it in GitHub Desktop.
Save pykello/c453e0ba413932ccb7d09aa327b75aca to your computer and use it in GitHub Desktop.
#include <iostream>
#include <chrono>
const int N = 4000;
int data[N][N];
void generate_data() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
data[i][j] = (i + j) & 3;
}
int sum1() {
int result = 0;
// add row-by-row
for (int x = 0; x < N * N; x+=4 /* 4 values at a time */) {
int row = x / N;
int col = x % N;
result += data[row][col] + data[row][col + 1] +
data[row][col + 2] + data[row][col + 3];
}
return result;
}
int sum2() {
int result = 0;
// add column-by-column
for (int x = 0; x < N * N; x+=4 /* 4 values at a time */) {
int row = x % N;
int col = x / N;
result += data[row][col] + data[row + 1][col] +
data[row + 2][col] + data[row + 3][col];
}
return result;
}
void measure_sum1() {
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
int result = sum1();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << "sum1: result=" << result << ", duration=" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl;
}
void measure_sum2() {
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
int result = sum2();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << "sum2: result=" << result << ", duration=" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl;
}
int main() {
generate_data();
measure_sum1();
measure_sum2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment