Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Created February 25, 2018 14:29
Show Gist options
  • Save royashbrook/d5f0e2f3976e6a720c1efb4e87ccd15a to your computer and use it in GitHub Desktop.
Save royashbrook/d5f0e2f3976e6a720c1efb4e87ccd15a to your computer and use it in GitHub Desktop.
void Main()
{
//function to measure an actions execution time
Func<Action,int,TimeSpan> ma = (m,c) =>{
Stopwatch s = new Stopwatch();
s.Start();
for (int i = 0; i < c; i++)
m();
s.Stop();
return s.Elapsed;
};
Random rnd = new Random(); //randomizer for our random numbers
int aw = 0; //counter for how many times A Method was faster
int rnc = 10000; //random number counter - how many random numbers to try
int tc = 1000; //test counter - how many tests to run against each random number
byte[] buffer = null; //init buffer for our Actions to use
//the two Actions to test
Action a = () => { var v = ((ushort)(buffer[0] << 8 | buffer[1])).ToString();};
Action b = () => { var v = ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 0))).ToString();};
//get this many random numbers
for (int r = 0; r < rnc; r++)
{
//populate the 'buffer' with some value up to 64k
buffer = BitConverter.GetBytes((UInt16)rnd.Next(0,65535));
//if the 'a' method is faster, increment it's win counter,
// test each random number 'tc' number of times
if(ma(a,tc) < ma(b,tc))
aw++;
}
//show the results
Console.WriteLine("Wins - A:{0} B:{1} - AWin% = {2}%", aw, rnc-aw, ((float)aw/rnc)*100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment