mercredi 25 avril 2018

C - series of if statements vs else if time messuring

I am sorry beforehand if my terminology is lacking. I wrote a code to demonstrate inefficiency of series of if statements vs else/if statements. And the results dont make any sense to me.

It's a simple algorithm that goes through an array (100000000 of elements) and counts occurrences of the elements, being 1,2,3,4,5 or else.

clock_t time1;
time1 = clock();
    for (int i=1; i<=n; i++)
    {
        if (arr[i]==1)
            p1++;
        if (arr[i]==2)
            p2++;
        if (arr[i]==3)
            p3++;
        if (arr[i]==4)
            p4++;
        if (arr[i]==5)
            p5++;
        if (!(arr[i]>=1 && arr[i]<=5))
            j++;
    }
time1 = clock() - time1;

printf("count of 1s:\t %d\n",p1);
printf("count of 2s:\t %d\n",p2);
printf("count of 3s:\t %d\n",p3);
printf("count of 4s:\t %d\n",p4);
printf("count of 5s:\t %d\n",p5);
printf("count of errors:\t %d\n",j);
printf("\n ---  counting took: %.10f ms---\n",((double)(time1)/CLOCKS_PER_SEC)*1000);

and then the same but with else if

clock_t time2;
time2 = clock();
    for (int i=1; i<=n; i++)
    {
        if (arr[i]==1)
            p1++;
        else if (arr[i]==2)
            p2++;
        else if (arr[i]==3)
            p3++;
        else if (arr[i]==4)
            p4++;
        else if (arr[i]==5)
            p5++;
        else j++;
    }
time2 = clock() - time2;

as expected when given an array of random values from 1 to 5 the else if is faster about two times BUT (here comes the confusion) when its given an array of thousand 1s I would expect the if series to take the same amount of time bc it has to check every condition even tho the first one is already true - but it takes HALF the time and when I give it array of only 5s it is also quicker.

Can anyone explain how it can be faster, please? - Thanks :/ (when I give it ran values from 4 to 5 it is actually takes about the same time as with values from 1 to 5)

(here are the results of the whole thing [ignore the Czech please])

Aucun commentaire:

Enregistrer un commentaire