C# 如何测量IComparer花了多长时间?
您好,我目前正在为我的项目的一部分编写一个测试计划,我想知道如何测量我的排序函数需要多长时间。我的尝试是这样的:C# 如何测量IComparer花了多长时间?,c#,winforms,performance,monitoring,icomparer,C#,Winforms,Performance,Monitoring,Icomparer,您好,我目前正在为我的项目的一部分编写一个测试计划,我想知道如何测量我的排序函数需要多长时间。我的尝试是这样的: private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e) { GameDB.Sort(new PlayerNameComparer()); currentEntryShown = 0; ShowData(); Upda
private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
}
但是我得到了一个编译器错误:
'DBProject.Form1.PlayerNameComparer.stopwatch'是一个“字段”,但像“类型”一样使用。
您在类区域中执行语句,而不是在方法中;)在PL语言中——>
Nie mozesz wykonywaćkodu w obrębie klasy,rób to w metodach:)
把它们放到方法中去
public int Compare(object x, object y)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int ret =((Player)x).playerIgName.CompareTo(((Player)y).playerIgName)
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
return ret;
}
但是,该代码会对您要排序的每个项目执行,因此最好在排序之前启动手表,然后像下面这样停止:)
这个答案是完全错误的,因为您使用的是
Compare
方法,在排序过程中会多次调用该方法
测试这一点的方法类似于:
private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GameDB.Sort(new PlayerNameComparer());
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
也考虑使用<代码> iMePARE.<代码>的泛型版本,因为它的强类型化,并且不需要从<代码>对象< /代码>类型中解压到您的<代码>类< /代码>类型。
一个很好的例子是:public class StringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
公共类StringComparer:IComparer
{
公共整数比较(字符串x、字符串y)
{
返回x.CompareTo(y);
}
}
在您的情况下,这可能会转化为:
public class PlayerNameComparer : IComparer<Player>
{
public int Compare(Player x, Player y)
{
return x.playerIgName.CompareTo(y.playerIgName);
}
}
公共类玩家比较者:IComparer
{
公共整数比较(玩家x,玩家y)
{
返回x.playerIgName.CompareTo(y.playerIgName);
}
}
不客气bracie:P别忘了检查答案是否有用:)也检查alexo的答案,他有一个优化代码的好主意
public class PlayerNameComparer : IComparer<Player>
{
public int Compare(Player x, Player y)
{
return x.playerIgName.CompareTo(y.playerIgName);
}
}