Skip to content

Instantly share code, notes, and snippets.

@bradphelan
Last active November 21, 2017 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradphelan/d140ab570e5416b27d682a9904a5cd1a to your computer and use it in GitHub Desktop.
Save bradphelan/d140ab570e5416b27d682a9904a5cd1a to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using devDept.Geometry;
using Xunit;
using Xunit.Abstractions;
namespace Weingartner.EyeShot.Spec
{
public class PerformanceSpec
{
private readonly ITestOutputHelper output;
public PerformanceSpec(ITestOutputHelper output)
{
this.output = output;
}
void LimitRange(double a, ref double i, double b)
{
if (i < a)
{
i = a;
}else
if (i > b)
{
i = b;
}
}
public interface Ord<T>
{
int Compare(T a, T b);
}
public struct OrdDouble : Ord<double>
{
public int Compare(double a, double b)
{
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
}
void LimitRangeGeneric<TOrd,T>(T a, ref T i, T b)
where TOrd : struct, Ord<T>
{
if (default(TOrd).Compare(i,a)<0)
{
i = a;
}else
if (default(TOrd).Compare( i,b )>0)
{
i = b;
}
}
[Fact]
public void LimitRangeIsEvil()
{
var s = Stopwatch.StartNew();
var sum = 0.0;
for (int i = 0; i < 1000000; i++)
{
var value = (double) i;
Utility.LimitRange( -1, ref value, 1);
sum += value;
}
output.WriteLine( $"Evil time = {s.ElapsedMilliseconds}" );
output.WriteLine( $"Sum = {sum}" );
sum = 0;
s = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
var value = (double) i;
LimitRange( -1, ref value, 1);
sum += value;
}
output.WriteLine( $"Good time = {s.ElapsedMilliseconds}" );
output.WriteLine( $"Sum = {sum}" );
sum = 0;
s = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
var value = (double) i;
LimitRangeGeneric<OrdDouble,double>( -1, ref value, 1);
sum += value;
}
output.WriteLine( $"Generic time = {s.ElapsedMilliseconds}" );
output.WriteLine( $"Sum = {sum}" );
}
}
}
Evil time = 32
Sum = 999999
Good time = 1
Sum = 999999
Generic time = 1
Sum = 999999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment