#include #include /* * If the following define is set to 0, the program will do * a pointer copy without doing a malloc/free around it (and * dereferencing that pointer, incidentally, would probably * cause a segfault. If you set it to 1, we will malloc memory * before doing the pointer copy, and after freeing it. * * How will the performance of your program change when you do * more copies in between the malloc() and free() calls? * * Can you describe the performance of both the pointer and struct * copies in terms of an equation? What are they? Does the * equation change for the pointer copy when you turn on * PTRTEST_WITH_MALLOC? How? */ #define PTRTEST_WITH_MALLOC 0 union tick_union { unsigned long long val64; struct { unsigned int low32; unsigned int hi32; } lowhi; }; inline unsigned long long ticks(void); inline unsigned long long ticks(void) { register union tick_union result; register unsigned int msr = 0; __asm __volatile( ".byte 0xf; .byte 0x31 # Read the cycle counter\n" " movl %%edx, %0 # high order bits\n" " movl %%eax, %1 # low order bits\n" : "=g" (result.lowhi.hi32), "=g" (result.lowhi.low32) : "g" (msr) : "eax", "edx" ); return(result.val64); } typedef struct my_struct_s my_struct_t; struct my_struct_s { char field1[80]; char field2[80]; char field3[8192]; int some_number; long other_number; my_struct_t *next; }; int main (void) { my_struct_t source, dest, *source_ptr, *dest_ptr; register int marker; long long start, end; marker = 1111; start = ticks(); #if PTRTEST_WITH_MALLOC > 0 source_ptr = (my_struct_t *)malloc(sizeof(my_struct_t)); if (source_ptr == 0) { return(1); } #endif /* PTRTEST_WITH_MALLOC > 0 */ /* If you add more copies to each case, you'll see the pointer copy outperform the struct copy */ dest_ptr = source_ptr; #if PTRTEST_WITH_MALLOC > 0 free(source_ptr); #endif /* PTRTEST_WITH_MALLOC > 0 */ end = ticks(); printf("pointer copy took %lld ticks\n", end - start); marker = 2222; start = ticks(); dest = source; end = ticks(); printf("struct copy took %lld ticks\n", end - start); marker = 3333; return 0; }