SE250:lab-1:vpup001

From Marks Wiki
Jump to navigation Jump to search

To see how long it takes to execute an addition operation in C, many millions of additions are done because a single addition is too fast to time on its own. This is done by using a ‘for loop’.

The variables t (of type clock_t), a=0 (of type long), i (of type int) and maxPoints = 10000000(of type int) were declared. The execution time is measured by using the clock() function (form #include<time.h>). In the loop, i is initialized to 0 and the condition is that it should be less than maxPoints and incremented by 1 (I++). The addition operation used is ‘incrementation of a (a++ = a = a+1)’. Each time the loop is executed, ‘a’ is incremented and this is repeated 10000000 times.

I found using 1 variable and incrementing it easier than using 2 variables and adding them but I will do it with 2 variable next time.

The clock() function notes the initial time (time before the loop is executed) and the final time (time after the loop is executed). So, the execution time is final time minus initial time. This time is the total time taken to perform the addition 10000000 times. The time is printed by using the ‘printf’ function.

The addition was done by using different data types. The data type of the variable ‘a’ is changed from ‘long’ to ‘int’, ‘short’, ‘float’ and double’. The answer was different in each case.

I have also noticed that there is a difference in the answer each time I run the program even if I use the same data type. So, a new ‘for loop’ is used (introduced a variable ‘j’ of type int) so that the previous loop is done 10 times and all the answers are printed to compare them. The previous loop is inside the new loop.

for (j=0; j<10; j++){
    t = clock();
    for (i=0; i<maxPoints; i++){
        a++;
    }
   printf("%ldmillisec\n", clock()-t);
}

The confusing part was whether to call the clock() function before the loop or inside the first loop. If the function is called before the 1st loop is executed it will calculate the time taken to execute the loop 10times so it is called after the 1st loop. After running the program, it is noticed that the 10 values are very random and different. Some of the values are double the others. Why are they so different???