Reputation: 8127
I was surprised when I benchmarked this function:
int f(int N = 999) {
int nMax = 0;
for (int i = 1; i <= N; ++i)
for (int j = i; j <= N; ++j) {
string digits = to_string(i*j);
string rDigits = digits;
reverse(rDigits.begin(), rDigits.end());
if (digits == rDigits)
nMax = max(i*j, nMax);
}
return nMax;
}
with VS2012, VS2013 (release, /O2) and MinGW 4.8.0, 4.8.1 (-Ofast) on Windows 7 32-bit and 64-bit. I noticed that MinGW built versions run about 13 times slower than VS ones. Is this a problem with implementation of to_string()
and reverse()
? Any other reasons?
The code I used is here: https://github.com/pauljurczak/Benchmark-2/blob/master/benchmark.cpp
EDIT
I narrowed down the problem to std::to_string()
function, which is about 16 times slower with MinGW then with VS. I used this snippet for testing:
int f(int N = 100000) {
int len = 0;
for (int i = 0; i <= N; ++i)
len += to_string(i).length();
return len;
}
When I compile it with g++ 4.7.3 on Ubuntu, performance is about the same as VS2012.
Upvotes: 2
Views: 1161
Reputation: 11
Check for C++ runtime version used by your MINGW build (use dependency walker or something similar). VS2012 supports r-values and perhaps in your case more importantly small string optimization. Using that would eliminate any memory allocation coming from to_string. Memory allocation requires significantly more CPU than finding max or reverse.
Upvotes: 1
Reputation: 1434
Visual Studio could have reversed the if
-condition:
if (digits != rDigits)
continue;
else
nMax = max(i*j, nMax);
But that is only a guess...
By the way, I would rather write:
string rDigits(digits.rbegin(), digits.rend());
And you could also take a look at: https://stackoverflow.com/a/17909430/1689664, it might give you some ideas to optimize your algorithm.
Upvotes: 1