QrazyNeo
QrazyNeo

Reputation: 65

C++ execution time test

Im testing this code:

string teststring = "";
int i = 0;

while ( i < 100000000 ) {

i++;

}

The execution time is: 0.359 s.

Then I try to do the exact same test again, but this time Ive added one extra line within the loop:

string teststring = "";
int i = 0;

while ( i < 100000000 ) {

i++;
teststring += "something random";


}

The execution time is 4 s.

Its one extra line, should it really take that much longer? Can I do something different to improve this?

Upvotes: 0

Views: 85

Answers (2)

Nicholas Pipitone
Nicholas Pipitone

Reputation: 4142

How would teststring += "something random"; be implemented? Something like:

str = "something random";
for( int i = 0; i < sizeof(str); i++ )
    teststring[teststring.length+i] = str[i];

Not to mention if teststring isn't big enough, it has to make a new region of memory twice as large, and copy every single byte over, and then continue (teststring will grow very large in your code, making that copy operation quite expensive). This is very complicated in comparison to i++, so it makes sense that the latter is much faster.

Upvotes: 4

mike
mike

Reputation: 1005

In addition to Nicholas Pipitone's point, an optimizing compiler can legitimately eliminate the original for loop and replace it with:

int i=100000001;

The optimizing compiler could do the same for the string concatentation, but it probably didn't bother catching that case (possibly because the string concatentation function may indicate it can throw exceptions, which the compiler may not know how to deal with).

Upvotes: 1

Related Questions