SE250:lab-1:sdal039
int main() { clock_t timeBefore, timeAfter, timeDiff, timeSum, timeAverage; long counter, repeatCounter; int sum; /* set initial timeSum value to 0 */ timeSum = 0; /*loop to repeat the process 100 times so an average value of */ /* time can be calculated */ for (repeatCounter = 0;repeatCounter < 100;repeatCounter++) { sum = 0; timeBefore = clock(); for (counter=0;counter < 10000000;counter++) { sum++; } timeAfter = clock(); timeDiff = (timeAfter - timeBefore); timeSum = timeSum + timeDiff; printf("Counter has been run: %d times.", repeatCounter); } /*create average time*/ timeAverage = timeSum / 100; printf("Sum: %d obtained after %ld something-seconds", sum, timeAverage); return 0; }
Not knowing how to get an actual value of time from the clock() function, the data collected is more for comparison rather than an actual useful value.
From the data collected below you can see what affect the variable type had on computing time. Int: 22 Long: 21 Short: 21 *see below Float: 82 Double: 82
Int and long took the least amount of time, float and double took the longest amount of time.
When first running the code I found that each time it ran, it gave a slightly different value for the time taken. While the difference wasn't much, I decided to add in another loop which would run the process 100 times and average the result. This process took a little longer, but it gave a vastly more accurate result.
As for 'short', I wasn't quite sure how to get a value for this. Being that it can't hold very large values, and that any value for the loop counter less than about 1,000,000 returned a time difference that was too small to accurately measure, running the program gave a sum of ~16,000 which I guess would be the minimum/maximum value that short can hold before it overflows.
In the code the loop increments the variable sum as well as the variable counter. When the line 'sum++' was removed, there was a slight difference in computing time for incrementing 2 variables versus incrementing 1 variable (21.4 versus 21.9).
All in all, for only starting learning C on Friday I feel that I have become a lot more comfortable with the language and hope that in future labs I will be able to focus more on the logic of what the question is asking, rather than how to actually code it.
Sdal039 11:48, 4 March 2008 (NZDT)