Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about loop speed

I have the following two loops:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;
int main(){

    int start=clock();
    for (int i=0;i<100;i++)
        cout<<i<<" "<<endl;
    cout<<clock()-start<<"\n"<<endl;
    cout<<"\n";

    int start1=clock();
    for (int j=0;j<100;++j)
        cout<<j<<" "<<endl;
    cout<<"\n";
    cout<<clock()-start1<<" \n "<<endl;

    return 0;
}

I ran that three times. On the first two runs, the second loop was fastest but, on the third run, the first loop was fastest. What does this mean? Which is better? Does it depend on the situation?

like image 427
dato datuashvili Avatar asked Aug 02 '10 07:08

dato datuashvili


2 Answers

The running time of your loops is overwhelmingly dominated by input-output operations. This means that the time you observe 1) has nothing to do with the actual performance of the loop (i.e. i++ vs ++j), 2) is pretty much unpredictable and unstable (essentially random).

In other words, your experiment is meaningless. It means absolutely nothing.

Finally, in situations when the result of the built-in ++ operator is not used, there is absolutely no difference between postfix and prefix increment. In any reasonable compiler both of your loops will have absolutely identical performance.

like image 81
AnT Avatar answered Oct 15 '22 00:10

AnT


In your case it is probably standard measurement error and it does not matter do you use post-increment or pre-increment. For standard types (int, byte ...) it does not matter.

BUT you should get used to using pre-increment because there are performance implications if you are using them on a Class, depending how those operators are implemented. Post-increment operator i++ has to make a copy of the object

For example:

class integer
{
public:
  integer(int t_value)
    : m_value(t_value)
  {
  }

  int get_value() { return m_value; }

  integer &operator++() // pre increment operator
  {
    ++m_value;
    return *this;
  }

  integer operator++(int) // post increment operator
  {
    integer old = *this; // a copy is made, it's cheap, but it's still a copy
    ++m_value;
    return old; // Return old copy
  }

private:
  int m_value;

Take a look at the following answer

StackOverflow: i++ less efficient than ++i, how to show this?

like image 38
Robert Vuković Avatar answered Oct 15 '22 00:10

Robert Vuković