Skip to content

Instantly share code, notes, and snippets.

@nsf
Created December 6, 2013 06:28
Show Gist options
  • Save nsf/7819447 to your computer and use it in GitHub Desktop.
Save nsf/7819447 to your computer and use it in GitHub Desktop.
Very interesting chunk of code and very interesting performance results.
#include <cstdio>
const int Size = 256;
static int opti_killer = 2;
int test1() {
int *buf = new int[Size*Size*2];
int out = 0;
#define bufget(buf, x, y, z) buf[y*Size+x+((z)%2)]
for (int z = 0; z < Size; z++) {
for (int y = 0; y < Size; y++) {
for (int x = 0; x < Size; x++) {
if (z == 0) {
bufget(buf, x, y, z) = y*Size+x;
} else {
bufget(buf, x, y, z) = bufget(buf, x, y, z-1)+opti_killer;
}
if (z == Size-1 && y == Size-1 && x == Size-1) {
out = bufget(buf, x, y, z);
}
}}}
#undef bufget
delete [] buf;
return out;
}
int test2() {
int *buf = new int[Size*Size*Size];
int out = 0;
#define bufget(buf, x, y, z) buf[((z)*Size+y)*Size+x]
for (int z = 0; z < Size; z++) {
for (int y = 0; y < Size; y++) {
for (int x = 0; x < Size; x++) {
if (z == 0) {
bufget(buf, x, y, z) = y*Size+x;
} else {
bufget(buf, x, y, z) = bufget(buf, x, y, z-1)+opti_killer;
}
if (z == Size-1 && y == Size-1 && x == Size-1) {
out = bufget(buf, x, y, z);
}
}}}
#undef bufget
delete [] buf;
return out;
}
int test1_n(int n) {
int out = 0;
for (int i = 0; i < n; i++) {
out += test1();
}
return out;
}
int test2_n(int n) {
int out = 0;
for (int i = 0; i < n; i++) {
out += test2();
}
return out;
}
const int N = 100;
int main(int argc, char **argv) {
if (argc == 1)
return 0;
if (argc < 999)
opti_killer = 1;
switch (argv[1][0]) {
case '1':
printf("starting 1\n");
printf("%d\n", test1_n(N));
break;
case '2':
printf("starting 2\n");
printf("%d\n", test2_n(N));
break;
default:
printf("unknown option: %c\n", argv[1][0]);
}
return 0;
}
/*
[nsf @ ~]$ g++ -O3 -o main main.cc
[nsf @ ~]$ time ./main 1
starting 1
6579000
real 0m2.636s
user 0m2.633s
sys 0m0.003s
[nsf @ ~]$ time ./main 2
starting 2
6579000
real 0m0.908s
user 0m0.490s
sys 0m0.417s
[nsf @ ~]$ clang++ -O3 -o main main.cc
[nsf @ ~]$ time ./main 1
starting 1
6579000
real 0m2.176s
user 0m2.177s
sys 0m0.000s
[nsf @ ~]$ time ./main 2
starting 2
6579000
real 0m1.938s
user 0m1.503s
sys 0m0.433s
[nsf @ ~]$ g++ --version
g++ (GCC) 4.8.2
[nsf @ ~]$ clang++ --version
clang version 3.3 (tags/RELEASE_33/final)
intel i5-3470 "Ivy Bridge"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment