Skip to content

Instantly share code, notes, and snippets.

@Vercidium
Last active February 20, 2020 21:48
Show Gist options
  • Save Vercidium/a51ee1b82df8cd474dd3e522add31922 to your computer and use it in GitHub Desktop.
Save Vercidium/a51ee1b82df8cd474dd3e522add31922 to your computer and use it in GitHub Desktop.
Performance benchmark for using Math.Sin(...) and Math.Cos(...) vs accessing values from a precalculated sine wave array.
ModelHelper.InitialiseTrigonometry();
Random rand = new Random();
int count = 524288;
float[] randoms = new float[count];
float[] result = new float[count];
int[] mathTimes = new int[100];
int[] arrayTimes = new int[100];
for (int c = 0; c < 100; c++)
{
for (int i = 0; i < count; i++)
randoms[i] = (float)(rand.NextDouble() * 100 - 50);
Stopwatch ss = new Stopwatch();
ss.Start();
for (int i = 0; i < count; i++)
{
var sin = Math.Sin(randoms[i]);
var cos = Math.Cos(randoms[i]);
}
mathTimes[c] = (int)ss.Elapsed.Ticks;
ss.Restart();
for (int i = 0; i < count; i++)
{
float sin, cos;
ModelHelper.GetSinAndCosCheap(randoms[i], out sin, out cos);
}
arrayTimes[c] = (int)ss.Elapsed.Ticks;
}
for (int i = 0; i < 100; i++)
Console.WriteLine(mathTimes[i]);
Console.WriteLine("\n-----\n");
for (int i = 0; i < 100; i++)
Console.WriteLine(arrayTimes[i]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment