1:using System; 2:using System.Collections.Generic; 3:using System.Text; 4: 5:namespace test_cs20 6:{ 7: class Program 8: { 9: static void calculatePI() 10: { 11: double pi = 0; // Accumulated value of pi 12: double ms = 0; // Elapsed time 13: int count = 0; // Number of iterations run 14: const int testTimeMS = 30000; // Run the test for 10 seconds 15: 16: LinearCongruentRnd rand = new LinearCongruentRnd(12345); 17: 18: hsTimer.init(); 19: hsTime start = hsTimer.getTime(); 20: do 21: { 22: // Random sampling method similar to the buffon needle experiment 23: double x, y; // Random coordinates -0.5...0.5 24: int inside=0; // Number of hits inside the circle 25: int outside=0; // Number of hits outside the circle 26: 27: // Run a bunch of samples 28: for (int samples=0; samples<10000000; samples++) 29: { 30: // Generate coordinates 31: x = rand.nextDouble() - 0.5; 32: y = rand.nextDouble() - 0.5; 33: 34: // Inside the circle? 35: if (x*x+y*y<0.25) 36: inside++; 37: else 38: outside++; 39: } 40: 41: // Calculate the value of pi 42: double new_pi = 4.0*inside/(inside+outside); 43: 44: // Accumulate it 45: pi += new_pi; 46: count++; 47: 48: // How long did this take? 49: ms = hsTimer.getElapsed(start); 50: } while (ms < testTimeMS); 51: 52: // PI is 53: System.Console.WriteLine("PI = " + pi/count); 54: System.Console.WriteLine("Iterations ran = " + count); 55: System.Console.WriteLine("Time = " + ms + " ms"); 56: System.Console.WriteLine("Iterations per second = " + 1000*count/ms); 57: } 58: 59: static void Main(string[] args) 60: { 61: calculatePI(); 62: } 63: } 64: 65: public struct hsTime 66: { 67: internal long ticks; 68: 69: internal hsTime(long v) 70: { 71: ticks = v; 72: } 73: } 74: 75: class hsTimer 76: { 77: public static void init() 78: { 79: } 80: 81: public static hsTime getTime() 82: { 83: return new hsTime(System.DateTime.Now.Ticks); 84: } 85: public static double getElapsed(hsTime start) 86: { 87: long ticks = System.DateTime.Now.Ticks - start.ticks; 88: return ticks/(double)System.TimeSpan.TicksPerMillisecond; 89: } 90: } 91: 92: class LinearCongruentRnd 93: { 94: 95: private System.UInt64 state; 96: 97: public LinearCongruentRnd(System.UInt64 start) 98: { 99: state = start; 100: } 101: 102: public System.UInt32 nextInt() 103: { 104: state = state*7919 + 104729; 105: return (System.UInt32)(state & 0xFFFFFFFF); 106: } 107: 108: public double nextDouble() 109: { 110: return (double)nextInt()/0xFFFFFFFF; 111: } 112: } 113:} 114:
Number of lines: 114