Skip to content

Instantly share code, notes, and snippets.

@chadbrewbaker
Created July 24, 2011 01:37
Show Gist options
  • Save chadbrewbaker/1102088 to your computer and use it in GitHub Desktop.
Save chadbrewbaker/1102088 to your computer and use it in GitHub Desktop.
Compare memory transfer speeds between the stack and the heap.
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
long TEST_SIZE = 500000;
long SAMPLES = 60000;
void my_copy(uint64_t* a, uint64_t* b, long n){
memcpy(b, a, n*sizeof(uint64_t));
}
int main () {
long i;
uint64_t stack[TEST_SIZE];
uint64_t stack2[TEST_SIZE];
uint64_t* heap = (uint64_t*) malloc(sizeof(uint64_t)*TEST_SIZE);
uint64_t* heap2 = (uint64_t*) malloc(sizeof(uint64_t)*TEST_SIZE);
// set some values:
for (i=0; i< TEST_SIZE; i++)
heap2[i]=stack2[i]=heap[i]=stack[i]=i%13;
for(i=0;i<SAMPLES;i++)
//my_copy(heap, stack, TEST_SIZE);
//my_copy(stack, heap, TEST_SIZE);
//my_copy(heap, heap2, TEST_SIZE);
my_copy(stack, stack2, TEST_SIZE);
return 0;
}
@chadbrewbaker
Copy link
Author

On the i7 Mac it seems that stack -> stack copies are a bit slower than heap -> heap copies which I found to be surprising.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment