- #1
- 2,076
- 140
Homework Statement
Not homework, but I'm wondering why a certain piece of code seems to run faster than another.
Homework Equations
The Attempt at a Solution
I'll mention a few relevant structs to be more clear:
Code:
struct intlist {
int *elems;
int capacity; /* Maximum number of elements in the list. */
int size; /* Current number of elements in the list */
};
typedef struct intlist IntList;
Here's a piece of code that prints out the heap allocated contents of elems:
Code:
/* Print the list pointed to by parameter list to the console.
* Terminate the program via assert if list is NULL.
*/
void intlist_print(const IntList *list){
assert(list != NULL);
if(list->size == 0)
printf("[]");
else{
clock_t tic = clock();
printf("[");
for(int i=0;i<list->size;i++)
i != list->size-1 ? printf("%d ", list->elems[i]) : printf("%d]", list->elems[i]);
clock_t toc = clock();
printf("\nElapsed time: %f seconds.\n", (double)(toc - tic) / CLOCKS_PER_SEC);
}
}
This code produces these results:
Code:
Expected output: [1 5 -3 9 1 5 -3 9 1 5]
Actual output: [1 5 -3 9 1 5 -3 9 1 5]
Elapsed time: 0.000002 seconds.
Now here's another piece of code, which does the same thing, but I originally thought would run faster:
Code:
void intlist_print(const IntList *list){
assert(list != NULL);
if(list->size == 0)
printf("[]");
else{
clock_t tic = clock();
printf("[");
for(int i = 0; i < list->size-1; i++)
printf("%d ", list->elems[i]);
printf("%d]", list->elems[list->size-1]);
clock_t toc = clock();
printf("\nElapsed time: %f seconds.\n", (double)(toc - tic) / CLOCKS_PER_SEC);
}
}
The results are below:
Code:
Expected output: [1 5 -3 9 1 5 -3 9 1 5]
Actual output: [1 5 -3 9 1 5 -3 9 1 5]
Elapsed time: 0.000003 seconds.
So for large enough ##n##, it would appear that the code without the implicit conditional runs slower for some reason. Why is this? I would think checking an extra if statement every loop would cost more time than simply iterating through the list and printing the contents. Is this related to something compiler or cpu specific?