我在两个项目中看似完全相同的C#代码基准测试存在问题。在两个项目中具有不同性能的相同方法
该代码是一个C#实现的绕数算法,以确定点是否在多边形内。
该列表是顶点有序列表,其经度为纬度&。从每个顶点绘制一条线时,按顺序绘制一个多边形,然后该方法确定该点是否位于多边形的内部。
下面是代码:
public static bool IsPointInPolygon(List<Vertex> polygon, Vertex point)
{
int wn = 0;
for (int i = 0; i < (polygon.Count - 1); i++)
{
if (polygon[i].Latitude <= point.Latitude)
{
if (polygon[i + 1].Latitude > point.Latitude)
{
if (IsLeft(polygon[i], polygon[i + 1], point) > 0)
wn++;
}
}
else
{
if (polygon[i + 1].Latitude <= point.Latitude)
{
if (IsLeft(polygon[i], polygon[i + 1], point) < 0)
wn--;
}
}
}
return wn != 0;
}
private static double IsLeft(Vertex lineStart, Vertex lineEnd, Vertex point)
{
return ((lineEnd.Longitude - lineStart.Longitude) * (point.Latitude - lineStart.Latitude)
- (point.Longitude - lineStart.Longitude) * (lineEnd.Latitude - lineStart.Latitude));
}
这里是我的顶点类:
public class Vertex
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Order { get; set; }
public Vertex(double latitude, double longitude)
{
this.Latitude = latitude;
this.Longitude = longitude;
}
public Vertex(double latitude, double longitude, int order)
{
this.Latitude = latitude;
this.Longitude = longitude;
this.Order = order;
}
}
这里是我用了这两个项目的基准代码(我使用的是并发袋,因为我在“*****”中并行处理):
System.Collections.Concurrent.ConcurrentBag<double> times = new System.Collections.Concurrent.ConcurrentBag<double>();
// *****
// *****
var start = DateTime.Now;
bool isPointInPoly = IsPointInPolygon(poly, point); // where poly is a List<Vertex> and point is a Vertex
var end = DateTime.Now;
times.Add((end - start).TotalMilliseconds);
// *****
// *****
Debug.WriteLine(times.Average());
在一个解决方案中,平均时间I返回大约为0.007 ms,但在另一个大约是0.014 ms的两倍。
在这两种解决方案中,我传递了一个相同的数据集,两个List的顺序相同,并且整个方法(称为多次)以相同顺序调用。
我的解决方案在“调试”和“发布”中进行了比较,并且都与“优化代码”标志集进行了比较,所有测试中性能差异的比率相同。
你能否提出一些我可以调整/调查的其他设置/代码问题,以便找出性能差异的原因?另外,如果您需要更多信息,请告诉我,我会提供。
更新: 我对这两个项目都运行了Visual Studio性能分析。这里是慢版:
http://i.imgur.com/kQamIUD.png
,这里是快速的版本:
http://i.imgur.com/UaVNcaM.png
道歉,我不能直接超链接的图片,我没有10美誉尚未。
感谢您回复马吕斯。我已将计时器更改为此,但结果相同。此外,我已经对5000 * 2350的进程进行了非常近似的计时,这个计划刚刚低于1200万次,其中一个项目的时间约为20秒,另一个项目的时间约为40秒。 此外,在我的整个数据集上运行时,性能差异很明显,所以我认为问题不在于计时器本身。 –