Reputation: 87
I tested my program and once decide to change BOOST_FOREACH
macros to the simple for
cycle with const_iterator
.
and i receive unexpected result: program work slower with for
.
Then i wrote small testing app:
std::vector<int> vec;
for (int i = 0; i != 50000000; ++i)
vec.push_back(i);
time_t t1 = clock();
int sum1 = 0;
for (std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it)
sum1 += *it;
std::cout << ulong(clock() - t1);
time_t t2 = clock();
int sum2 = 0;
BOOST_FOREACH(auto &it, vec) {
sum2 += it;
}
std::cout << ulong(clock() - t2);
here is output:
34963
26964
Why so?
Upvotes: 0
Views: 72
Reputation: 356
You have undefined behaviour in your code. The sum of 0+...+50,000,000 is way beyond MAX_INT. Integer overflow == undefined behavior , undefined behavior== your tests are invalid.
Assuming you built the project with full optimizations on, I'm guessing the results happen because of CPU warm-up and due the fact that In the second benchmark, some of the data is already cached. Try switching the benchmarkimg tests and see what happens
Upvotes: 5