using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace ForEach_Example { public class Timer { [DllImport("KERNEL32"), System.Security.SuppressUnmanagedCodeSecurityAttribute()] private static extern int QueryPerformanceCounter(out long time); [DllImport("KERNEL32"), System.Security.SuppressUnmanagedCodeSecurityAttribute()] private static extern int QueryPerformanceFrequency(out long freq); private long _freq; private long _start; private long _stop; public Timer() { QueryPerformanceFrequency(out _freq); } public Timer(int maxSamples) { QueryPerformanceFrequency(out _freq); } public void Start() { QueryPerformanceCounter(out _start); } public void Stop() { QueryPerformanceCounter(out _stop); } public double Seconds { get { return ((double)(_stop - _start)) / (double)_freq; } } public double Milliseconds { get { return Seconds * 1000; } } public long Ticks { get { return _stop - _start; } } } class Program { static void Main(string[] args) { bool b; Timer _timer = new Timer(); BitArray newBitArray = new BitArray(1000, false); int variation = (args.Length > 0) ? Int32.Parse(args[0]) : 2; switch (variation) { case 1: _timer.Start(); for (int j = 0; j < 1000; j++) { for (int i = 0; i < newBitArray.Count; i++) { b = newBitArray[i]; } } _timer.Stop(); Console.WriteLine("Total Time for Indexed based access = {0}", _timer.Seconds); break; case 2: _timer.Start(); for (int j = 0; j < 1000; j++) { foreach (bool b2 in newBitArray) { b = b2; } } _timer.Stop(); Console.WriteLine("Total Time for enumerator = {0}", _timer.Seconds); break; } } } }