Thread: while() vs for()

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    68

    while() vs for() **Update..post 12**

    Is there a difference in the efficiency of while loops compared to for loops?

    I was marked off 10% on my project because I used a while instead of for, nothing else on this project was wrong. I never even thought about the difference of these loops until today. I guess this is one of those Mind = Blown moments.

    The program multiplied matrices, allowed the user to change them, and a few other minor things.
    Last edited by madmax2006; 02-21-2010 at 07:14 PM.

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Is there a difference in the efficiency of while loops compared to for loops?
    No. Or, you can't definitively say. But if you have a while loop and a for loop that do the same thing, any compiler that isn't complete garbage will emit the same code.

    If you did something like:
    Code:
    i = 0;
    while(i < 5)
    {
      i++;
    }
    I can see marking you down, because you just wrote a for loop in a slightly less idiomatic manner. There's nothing wrong with the while loop, per se, but it would show that you didn't recognize when to use a very common statement.

  3. #3
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    There shouldn't be any difference in efficiency.
    I used to use this test to decide whether to use a while or a for:

    If you can print out the number of times the loop will execute before entering the loop, use a for. Otherwise use a while.

    Note that this is only a rough guideline and there are many exceptions. For example, you may need to break out of a for loop or writing something like while (i-- > 0){...} is fairly common.

    But bottom line: Using the correct construct is very important to make your code understandable. So you may think 10% is harsh, but your teacher is being hard on you to teach you a good lesson. You can post the loop in question here if you'd like for us to judge.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int main()
    {
    	double start, finish, elapsed;
    	int temp1, temp2;
    
    	start = (double) clock()/CLOCKS_PER_SEC;
    
    	temp2 = 0;
    	for(temp1 = 0; temp1<1000000000; temp1++)
    	{
    		temp2 = temp2+1;
    	}
    
    	finish = (double) clock()/CLOCKS_PER_SEC;
    	elapsed = finish-start;
    
    	printf("The elapsed time is %lf seconds\n", elapsed);
    
    	return;
    }
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int main()
    {
    	double start, finish, elapsed;
    	int temp1, temp2;
    
    	start = (double) clock()/CLOCKS_PER_SEC;
    
    	temp1 = 0, temp2 = 0;
    	while(temp1 < 1000000000)
    	{
    		temp2 = temp2+1;
    		temp1++;
    	}
    
    	finish = (double) clock()/CLOCKS_PER_SEC;
    	elapsed = finish-start;
    
    	printf("The elapsed time is %lf seconds\n", elapsed);
    
    	return;
    }
    Anybody else want to run this code & see what results they get?

    I have gotten that the while loop is actually 1/100 th of a second faster (.01).

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If I know that a loop must be entered, then I want a for loop, or a do while. A regular while loop I use to test whether any looping is necessary first. If I know how many times the loop must iterate, then a for loop is my choice.

    I don't believe you were (or should be), marked down for clarity. EDIT: I looked an found nothing dealing with while loops and tail recursion, right now, so I'm deleting that reference.

    The classic while loop from Quicksort is illustrative:

    while(a[j] > pivot) --j; //hi index decrementing

    Here, you definitely NEED a while loop, because 1) You don't want to even enter the loop, if it's not appropriate, and 2) You have no idea how many times this loop will iterate, on any of the several sub-arrays that will be passed to it.

    That's as clear as anything you can do with a for loop, imo.

    I tested these two types of loops out on my old Turbo C ver. 1.01 compiler some years back - I saw no difference, but it wasn't an exhaustive analysis, either.

    To be fair, you should be marked down ONLY as much as the difference shown in testing, for those two loops, on the teacher's computer. Maybe 0% - 1%.

    Edit: Sure, I'll run your test program.

    On Turbo C ver. 1.01, both programs had to be changed to an unsigned long int data type, but they both ran in exactly the same time:
    4.120879 seconds, under WindowsXP
    Last edited by Adak; 02-21-2010 at 06:15 PM.

  6. #6
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    Thanks - anybody else mind running it as well? I'm going to get this 10% of my project grade back.

  7. #7
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Both run in 0.000000 seconds with GCC 4.4, highest optimization level.

    It probably recognized that the variables aren't used anyways, and optimized them out completely.

    Even if I add a printf statement at the end, GCC still optimizes them out, even at just -O1, because it recognized that the final value of temp2 is always the same.

    With optimization turned off completely (-O0), they both finish in 2.15 seconds.

  8. #8
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    BTW, depending on how big the project is, 10% may be way too much.

    And the issue is only idiomatic. There should not be any difference in efficiency.

    Did the teacher say the reason is efficiency? Or are you guessing?

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    It was 300 lines of code - and she said quote -
    "Individual Comments : In multMatrices, it would be more efficient to use for loops instead of while loops. "

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I would ask her to give you an example of it, or show you how to change your code to make this "increase in efficiency". She may be right, but if so, she should be able to show what she's talking about.

  11. #11
    Registered User
    Join Date
    Mar 2007
    Posts
    416
    Efficiency can be measured in many ways. Performance, code writing, algorithms, etc. Each is relative to a certain aspect/person since each will change given different circumstances. Although I agree 10% for using a while instead of a for (especially if it still completes the same job) is kind of harsh, I agree with the professors statement.

  12. #12
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    Edit - ID 10 T error.
    Last edited by madmax2006; 02-21-2010 at 11:20 PM.

  13. #13
    Registered User
    Join Date
    Mar 2007
    Posts
    416
    use some optimization flags like -O2 or something, then see what it gives.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    So what did your actual code look like? The initialization, and the loop call. Not some theoretical speed test, but what you actually wrote.


    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Individual Comments : In multMatrices, it would be more efficient to use for loops instead of while loops.
    Uninformed comment. There are no two ways about it. There are some statements you can be fairly confident about when it comes to optimization, but this is not one of them. When it comes to choosing a loop, you should pick the one that makes sense given the task at hand. This is absolutely not the place for premature optimization. Let the compiler do its job.

    In your “for is almost twice as fast” code, you have a bug: you're incrementing temp1 twice in the “for” version. Remove the temp1++ at the end of the loop and test again.

Popular pages Recent additions subscribe to a feed