Skip to content

Instantly share code, notes, and snippets.

@awreece
Last active December 17, 2015 07:09
Show Gist options
  • Save awreece/5571138 to your computer and use it in GitHub Desktop.
Save awreece/5571138 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>
// #include <smmintrin.h>
// #include <emmintrin.h>
#define SAMPLES 5
#define SIZE (1024*1024*1024)
uint64_t array[SIZE/sizeof(uint64_t)];
#define to_bw(usec) ((SIZE/(1024.0 * 1024.0 * 1024.0)) / (usec/(1000.0*1000.0)))
void write_memory() {
// __m128 const vals = _mm_set1_ps(1.0);
size_t i;
float* fbase = (float*) array;
for (i = 0; i < SIZE / sizeof(float); i += sizeof(float)) {
// _mm_stream_ps(&fbase[i], vals);
fbase[i] = 0;
}
}
void read_memory() {
float accum = 0;
size_t i;
float* fbase = (float*) array;
for (i = 0; i < SIZE / sizeof(float); i += sizeof(float)) {
accum += fbase[i];
}
// This is unlikely, and we want to make sure the reads are not optimized
// away.
assert(accum != (float) 0xDEADBEEF);
}
void timeit(void (*function)(), char* name) {
size_t min_usec = 9999999999;
size_t i;
for (i = 0; i < SAMPLES; i++) {
struct timeval before, after, total;
gettimeofday(&before, NULL);
function();
gettimeofday(&after, NULL);
timersub(&after, &before, &total);
assert(total.tv_sec == 0);
if (total.tv_usec < min_usec) {
min_usec = total.tv_usec;
}
}
double usec = min_usec;
printf("%s: %.2f ms\n", name, usec / 1000.0);
printf("%s: %.2f GiB/s\n", name, to_bw(usec));
}
int main() {
// Memory must be 16 byte aligned.
assert(((uintptr_t) array) % 16 == 0);
assert((SIZE % 16) == 0);
timeit(read_memory, "read");
timeit(write_memory, "write");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment