This code example will output time: 0
regardless of the value of N
when compiled with Visual Studio Professional 2013 Update 3 in release mode, both 32 and 64-bit option:
#include <iostream>
#include <functional>
#include <ctime>
using namespace std;
void bar(int i, int& x, int& y) {x = i%13; y = i%23;}
int g(int N = 1E9) {
int x, y;
int r = 0;
for (int i = 1; i <= N; ++i) {
bar(i, x, y);
r += x+y;
}
return r;
}
int main()
{
auto t0 = clock();
auto r = g();
auto t1 = clock();
cout << r << " time: " << t1-t0 << endl;
return 0;
}
When tested with gcc, clang and other version of vc++ on rextester.com, it behaves correctly and outputs time
greater than zero. Any clues what is going on here?
I noticed that inlining the g()
function restores correct behaviour, but changing declaration and initialization order of t0
, r
and t1
does not.