Skip to content

Instantly share code, notes, and snippets.

@ericliang
Created July 29, 2013 15:43
Show Gist options
  • Save ericliang/6105284 to your computer and use it in GitHub Desktop.
Save ericliang/6105284 to your computer and use it in GitHub Desktop.
Illustrate processor cache effects
#include <iostream>
#include <sys/time.h>
using namespace std;
//http://igoro.com/archive/gallery-of-processor-cache-effects/
int print_interval(timeval t1, timeval t2){
double elapsed;
elapsed = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsed += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
cout<<elapsed<<"\t";
}
int steps = 64*1024*1024;
int update_every_kth(int size, int k){
timeval t1, t2;
double elapsed;
gettimeofday(&t1, NULL);
int* arr = new int[size];
int size_mod = size-1;
for(int i=0; i<steps; i++){
arr[(i*16)&size_mod]++;
}
gettimeofday(&t2, NULL);
cout<<k<<":";
print_interval(t1,t2);
delete arr;
return 0;
}
//For hardware complexity
static int a,b,c,d,e,f,g;
static int wired(){
a=b=c=d=e=f=g=0;
timeval t1, t2, t3, t4;
gettimeofday(&t1, NULL);
for(int i=0; i<400000000; i++) {
a++,b++,c++,d++;
//a++,c++,e++,g++;
}
gettimeofday(&t2, NULL);
for(int i=0; i<400000000; i++) {
//a++,b++,c++,d++;
a++,c++,e++,g++;
}
gettimeofday(&t3, NULL);
for(int i=0; i<400000000; i++) {
a++,c++;
}
gettimeofday(&t4, NULL);
cout<<"1: ";
print_interval(t1,t2);
cout<<"2: ";
print_interval(t2,t3);
cout<<"3: ";
print_interval(t3,t4);
cout<<"\n";
// cout <<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\n";
return 0;
}
int main()
{
for(int i=0; i<20; i++){
wired();
}
int max_size = 64*1024*1024;
for(int j=1024; j<=max_size; j*=2){
cout << j <<"\t";
for(int i=1; i<257; i*=2){
update_every_kth(j, i);
}
cout<<"\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment