1:// test_cpp.cpp : Defines the entry point for the console application. 2:// 3:#include "hsTimer.h" 4:#include <stdlib.h> 5:#include <iostream> 6:#include <tchar.h> 7:#include <math.h> 8: 9:using namespace std; 10:using namespace MobyDisk; 11: 12:class LinearCongruentRnd { 13: 14:private: 15: __int64 state; 16: 17:public: 18: LinearCongruentRnd(int start) { 19: state = start; 20: } 21: 22: unsigned int nextInt() 23: { 24: state = state*7919 + 104729; 25: return static_cast<unsigned int>(state & 0xFFFFFFFF); 26: } 27: 28: double nextDouble() { 29: return (double)nextInt()/UINT_MAX; 30: } 31:}; 32: 33:void calculatePI() 34:{ 35: double pi = 0; // Accumulated value of pi 36: double ms = 0; // Elapsed time 37: int count = 0; // Number of iterations run 38: static const int testTimeMS = 10000; // Run the test for 10 seconds 39: 40: LinearCongruentRnd rand(12345); 41: 42: hsTimer::init(); 43: hsTime start = hsTimer::getTime(); 44: do 45: { 46: // Random sampling method similar to the buffon needle experiment 47: double x,y; // Random coordinates -0.5...0.5 48: int inside=0; // Number of hits inside the circle 49: int outside=0; // Number of hits outside the circle 50: 51: // Run a bunch of samples 52: for (int samples=0; samples<10000000; samples++) 53: { 54: // Generate coordinates 55: x = rand.nextDouble() - 0.5; 56: y = rand.nextDouble() - 0.5; 57: 58: // Inside the circle? 59: if (x*x+y*y<0.25) 60: inside++; 61: else 62: outside++; 63: } 64: 65: // Calculate the value of pi 66: double new_pi = 4*static_cast<double>(inside)/(inside+outside); 67: 68: // Accumulate it 69: pi += new_pi; 70: count++; 71: 72: // How long did this take? 73: ms = hsTimer::getElapsed(start); 74: } while (ms < testTimeMS); 75: 76: // PI is 77: cout << "PI = " << pi/count << endl; 78: cout << "Iterations ran = " << count << endl; 79: cout << "Time = " << ms << " ms" << endl; 80: cout << "Iterations per second = " << 1000*count/ms << endl; 81:} 82: 83: 84:int _tmain(int argc, _TCHAR* argv[]) 85:{ 86: 87: calculatePI(); 88: 89: return 0; 90:}
Number of lines: 90