C++和其他语言不同的地方,就是可以做底层优化,我来试一下。在我的机器上,使用VC2013 32bit:
问题原C++版本 156ms
grapeot的版本 23ms
我觉得用32位浮点数比较精确,改了一下:
// milo_float
#include
#include
#include
using namespace std;
class LCG {
public:
LCG(uint32_t seed) : mSeed(seed) {}
float operator()() {
mSeed = mSeed * 214013 + 2531011;
union {
uint32_t u;
float f;
}u = { (mSeed >> 9) | 0x3F800000 };
return u.f - 1.0f;
}
private:
uint32_t mSeed;
};
void main()
{
LARGE_INTEGER st;
QueryPerformanceCounter(&st);
const unsigned simulate_total = 2500000;
unsigned inside_count = 0;
LCG rng(0);
for (unsigned i = 1; i < simulate_total; i++){
float a = rng();
float b = rng();
if (a * a + b * b < 1.0f)
inside_count++;
a = 1.0f - a;
b = 1.0f - b;
if (a * a + b * b < 1.0f)
inside_count++;
}
LARGE_INTEGER end, freq;
QueryPerformanceCounter(&end);
QueryPerformanceFrequency(&freq);
cout << inside_count / double(simulate_total) * 2 << endl;
cout << (end.QuadPart - st.QuadPart) * 1000.0 / freq.QuadPart << endl;
}