Skip to content

Instantly share code, notes, and snippets.

@travisdowns
Created July 20, 2017 02:34
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 travisdowns/7b966de932debfec39c731b2732af91a to your computer and use it in GitHub Desktop.
Save travisdowns/7b966de932debfec39c731b2732af91a to your computer and use it in GitHub Desktop.
/* https://stackoverflow.com/questions/20697215/when-should-we-use-prefetch */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <emmintrin.h>
#define MIB (1024 * 1024)
#define ELEM int
#define SIZE (256 * MIB) // 64 MiB
#define ELEMS (SIZE / sizeof(ELEM))
#define STEP (64 / sizeof(ELEM))
#define REP 10
#define ITER 10
int main(int argc, char **argv) {
int do_off = (argc == 1 || strcmp(argv[1], "off") == 0);
int do_on = (argc == 1 || strcmp(argv[1], "on") == 0);
ELEM *a = aligned_alloc(4096, SIZE);
for (int i = 0; i < ELEMS; ++i) {
a[i] = i + 1;
}
for (int try = 0; try < ITER; try++) {
unsigned long long int sum = 0;
struct timeb start, end;
unsigned long long delta;
if (do_off) {
ftime(&start);
for (int r = 0; r < REP; r++) {
for (int i = 0; i < ELEMS; i += STEP) {
sum += a[i];
}
}
ftime(&end);
delta = (end.time * 1000 + end.millitm) - (start.time * 1000 + start.millitm);
printf("Prefetching off: SIZE=%d MiB, sum=%lld, time=%3lld, MiB/s=%lld\n",
SIZE / MIB, sum, delta, (long long)REP * SIZE * 1000 / (MIB * delta));
}
if (do_on) {
sum = 0;
ftime(&start);
for (int r = 0; r < REP; r++) {
for (int i = 0; i < ELEMS; i += STEP) {
sum += a[i];
_mm_prefetch(&a[i + 4096/sizeof(ELEM)], _MM_HINT_T0);
}
}
ftime(&end);
delta = (end.time * 1000 + end.millitm) - (start.time * 1000 + start.millitm);
printf("Prefetching on: SIZE=%d MiB, sum=%lld, time=%3lld, MiB/s=%lld\n",
SIZE / MIB, sum, delta, (long long)REP * SIZE * 1000 / (MIB * delta));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment