Test Results (Dual core, x86):
''''''''''''''''''''' DEBUG MODE '''
= 1 =
Division took 00:00:06.2482408 ms
BuiltInSign took 00:00:05.0293383 ms <<<
BitTestSign took 00:00:05.2092181 ms
CustomSign took 00:00:05.2512802 ms
= 2 =
Division took 00:00:06.2477787 ms
BuiltInSign took 00:00:05.0330921 ms <<<
BitTestSign took 00:00:05.2114098 ms
CustomSign took 00:00:05.2556966 ms
= 3 =
Division took 00:00:06.2506690 ms
BuiltInSign took 00:00:05.0388615 ms <<<
BitTestSign took 00:00:05.2306954 ms
CustomSign took 00:00:05.2512391 ms
''''''''''''''''''' RELEASE MODE '''
= 1 =
Division took 00:00:01.0974078 ms
BuiltInSign took 00:00:00.3195232 ms
BitTestSign took 00:00:00.6392142 ms
CustomSign took 00:00:00.3194230 ms <<<
= 2 =
Division took 00:00:01.1007138 ms
BuiltInSign took 00:00:00.3197784 ms <<<
BitTestSign took 00:00:00.6395294 ms
CustomSign took 00:00:00.3202774 ms
= 3 =
Division took 00:00:01.0977087 ms
BuiltInSign took 00:00:00.3194622 ms <<<
BitTestSign took 00:00:00.6394220 ms
CustomSign took 00:00:00.3201607 ms
Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Stopwatch sw = new Stopwatch();
MyEnum myEnum = MyEnum.None;
const int max = 100000000;
sw.Start();
for (int i = -max; i < max; i++)
{
myEnum = Division(i);
}
sw.Stop();
Console.WriteLine("Division took {0} ms", sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = -max; i < max; i++)
{
myEnum = BuiltInSign(i);
}
sw.Stop();
Console.WriteLine("BuiltInSign took {0} ms", sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = -max; i < max; i++)
{
myEnum = BitTestSign(i);
}
sw.Stop();
Console.WriteLine("BitTestSign took {0} ms", sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = -max; i < max; i++)
{
myEnum = CustomSign(i);
}
sw.Stop();
Console.WriteLine("CustomSign took {0} ms", sw.Elapsed);
}
private MyEnum Division(int value)
{
return value == 0 ? 0 : (MyEnum)(value / Math.Abs(value));
}
private MyEnum BuiltInSign(int value)
{
return (MyEnum)Math.Sign(value);
}
private MyEnum CustomSign(int value)
{
if (value < 0)
return MyEnum.Neg;
if (value > 0)
return MyEnum.Pos;
return MyEnum.None;
}
MyEnum BitTestSign(int value)
{
// Shifts the variable over 31 places,
// if the MSB is 1, the statement is true
if ((value >> 31) == 1)
{
return MyEnum.Neg;
}
else
{
if (value == 0)
{
return MyEnum.None;
}
else
{
return MyEnum.Pos;
}
}
}
private enum MyEnum
{
Pos = 1,
None = 0,
Neg = -1
}
}