Skip to content

Instantly share code, notes, and snippets.

@temoto
Created September 3, 2012 20:07
Show Gist options
  • Save temoto/3612972 to your computer and use it in GitHub Desktop.
Save temoto/3612972 to your computer and use it in GitHub Desktop.
Various elementary CPU operations benchmark
# gcc -O3 -o cpu-perf-test -lrt cpu-perf-test.cxx && (for x in {1..7}; do sleep 0.3s; ./cpu-perf-test; done) && rm cpu-perf-test
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
//const char *op_tag = "id "; long op(long x) { return x; }
const char *op_tag = "*2 "; long op(long x) { return x * 2; }
//const char *op_tag = "<<1"; long op(long x) { return x << 1; }
//const char *op_tag = "*27"; long op(long x) { return x * 27; }
//const char *op_tag = "*31"; long op(long x) { return x * 31; }
long f1(long *a, long size) {
long sum = 0;
for (long i = 0; i < size; i++) {
sum += op(a[i]);
}
return sum;
}
long long diff(timespec *t1, timespec *t2) {
return ((t2->tv_sec - t1->tv_sec) * 1e9) + (t2->tv_nsec - t1->tv_nsec);
}
int main() {
timespec t1, t2;
long size = 1000000;
long *a = (long*)malloc(sizeof(long) * size);
// fill with interesting values
a[0] = 7;
for (long i = 1; i < size; i++) {
a[i] = a[i - 1] * 137 + 5;
}
if (clock_gettime(CLOCK_MONOTONIC_RAW, &t1)) {
perror("clock_gettime t1");
return 1;
}
long sum = f1(a, size) + f1(a, size);
if (clock_gettime(CLOCK_MONOTONIC_RAW, &t2)) {
perror("clock_gettime t2");
return 1;
}
long long time = diff(&t1, &t2);
if (time == 0) {
fprintf(stderr, "measured time difference = 0\n");
return 1;
}
printf("op: %s result: %Ld size: %Ld time: %Ld speed: %Ld\n", op_tag, sum, size, time, size * 1000000 / time);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment